import { StyleTransformer } from './styleToTailwind';

const logger: any = function (msg) {};

// 基础颜色映射表（仅包含最常用的基础颜色）
const colorMap: Record<string, string> = {
  // '#ffffff': 'white',
  // '#000000': 'black',
};

// HEX转Tailwind类名
const toTailwindColor = (hex: string) => {
  // 如果是CSS变量格式，直接使用中括号语法
  if (hex.startsWith('var(--')) {
    return `[${hex}]`;
  }

  const normalizedHex = hex.toLowerCase();
  // 检查是否存在于基础颜色映射中
  if (colorMap[normalizedHex]) {
    // 直接返回颜色名称，不转换为CSS变量
    return colorMap[normalizedHex];
  }
  // 对于其他所有颜色，直接使用原始HEX值
  return `[${hex}]`;
};

// 尺寸单位转换（4px = 1单位）
const pxToUnit = (px: string) => {
  // 处理百分比单位
  if (px.includes('%')) {
    return px; // 保持百分比不变
  }

  // 处理其他非px单位（如em, rem, vh, vw等）
  if (px.match(/[a-z]+$/) && !px.endsWith('px')) {
    return px; // 保持其他单位不变
  }

  // 处理px单位
  return Math.round(parseInt(px.replace('px', '')) / 4).toString();
};

// 解析线性渐变为 Tailwind 类名
const parseLinearGradientToTailwind = (value: string, isTextGradient: boolean = false): string => {
  // 匹配线性渐变的完整格式，支持角度、方向关键字和颜色停止点
  const gradientMatch = value.match(/^linear-gradient\(\s*([^,]+)\s*,\s*(.+)\)$/);
  if (!gradientMatch) {
    return `bg-[${value}]`;
  }

  const [, direction, colorsStr] = gradientMatch;

  // 解析方向
  const angleMap: Record<string, string> = {
    '0deg': 'to-t',
    '90deg': 'to-r',
    '180deg': 'to-b',
    '270deg': 'to-l',
    '45deg': 'to-tr',
    '135deg': 'to-br',
    '225deg': 'to-bl',
    '315deg': 'to-tl',
    'to top': 'to-t',
    'to right': 'to-r',
    'to bottom': 'to-b',
    'to left': 'to-l',
    'to top right': 'to-tr',
    'to bottom right': 'to-br',
    'to bottom left': 'to-bl',
    'to top left': 'to-tl',
  };

  const normalizedDirection = direction.trim();
  let tailwindDirection = angleMap[normalizedDirection];

  // 如果不是标准角度，对于复杂角度使用完整的渐变语法
  if (!tailwindDirection) {
    // 对于非标准角度，直接使用完整的渐变语法而不是错误的 to-[angle] 格式
    const colorStops = parseColorStops(colorsStr);
    const colorString = colorStops.map((stop) => stop.color).join(', ');
    let result = [`bg-[linear-gradient(${normalizedDirection}, ${colorString})]`];

    // 如果是文本渐变，添加 clip-text 相关类
    if (isTextGradient) {
      result.push(
        '[WebkitBackgroundClip:text]',
        '[WebkitTextFillColor:transparent]',
        '[backgroundClip:text]',
      );
    }

    return result.join(' ');
  }

  // 解析颜色停止点，支持复杂格式
  const colorStops = parseColorStops(colorsStr);

  let result = [`bg-gradient-${tailwindDirection}`];

  if (colorStops.length >= 2) {
    result.push(`from-[${colorStops[0].color}]`);

    // 处理中间色（via）
    for (let i = 1; i < colorStops.length - 1; i++) {
      result.push(`via-[${colorStops[i].color}]`);
    }

    result.push(`to-[${colorStops[colorStops.length - 1].color}]`);
  }

  // 如果是文本渐变，添加 clip-text 相关类
  if (isTextGradient) {
    result.push(
      '[WebkitBackgroundClip:text]',
      '[WebkitTextFillColor:transparent]',
      '[backgroundClip:text]',
    );
  }

  return result.join(' ');
};

// 解析线性渐变为 Tailwind 类名 (支持标准颜色)
const parseLinearGradientToTailwindWithStandardColors = (
  value: string,
  isTextGradient: boolean = false,
): string => {
  // 匹配线性渐变的完整格式，支持角度、方向关键字和颜色停止点
  const gradientMatch = value.match(/^linear-gradient\(\s*([^,]+)\s*,\s*(.+)\)$/);
  if (!gradientMatch) {
    return `bg-[${value}]`;
  }

  const [, direction, colorsStr] = gradientMatch;

  // 解析方向
  const angleMap: Record<string, string> = {
    '0deg': 'to-t',
    '90deg': 'to-r',
    '180deg': 'to-b',
    '270deg': 'to-l',
    '45deg': 'to-tr',
    '135deg': 'to-br',
    '225deg': 'to-bl',
    '315deg': 'to-tl',
    'to top': 'to-t',
    'to right': 'to-r',
    'to bottom': 'to-b',
    'to left': 'to-l',
    'to top right': 'to-tr',
    'to bottom right': 'to-br',
    'to bottom left': 'to-bl',
    'to top left': 'to-tl',
  };

  const normalizedDirection = direction.trim();
  let tailwindDirection = angleMap[normalizedDirection];

  // 如果不是标准角度，对于复杂角度使用完整的渐变语法
  if (!tailwindDirection) {
    // 对于非标准角度，直接使用完整的渐变语法而不是错误的 to-[angle] 格式
    const colorStops = parseColorStops(colorsStr);
    const colorString = colorStops.map((stop) => stop.color).join(', ');
    let result = [`bg-[linear-gradient(${normalizedDirection}, ${colorString})]`];

    // 如果是文本渐变，添加 clip-text 相关类
    if (isTextGradient) {
      result.push(
        '[WebkitBackgroundClip:text]',
        '[WebkitTextFillColor:transparent]',
        '[backgroundClip:text]',
      );
    }

    return result.join(' ');
  }

  // 解析颜色停止点，支持复杂格式
  const colorStops = parseColorStops(colorsStr);

  let result = [`bg-gradient-${tailwindDirection}`];

  if (colorStops.length >= 2) {
    // 转换第一个颜色 (from)
    const fromColor = convertCSSColorToTailwind(colorStops[0].color);
    result.push(fromColor.startsWith('from-') ? fromColor : `from-${fromColor}`);

    // 处理中间色（via）
    for (let i = 1; i < colorStops.length - 1; i++) {
      const viaColor = convertCSSColorToTailwind(colorStops[i].color);
      result.push(viaColor.startsWith('via-') ? viaColor : `via-${viaColor}`);
    }

    // 转换最后一个颜色 (to)
    const toColor = convertCSSColorToTailwind(colorStops[colorStops.length - 1].color);
    result.push(toColor.startsWith('to-') ? toColor : `to-${toColor}`);
  }

  // 如果是文本渐变，添加 clip-text 相关类
  if (isTextGradient) {
    result.push(
      '[WebkitBackgroundClip:text]',
      '[WebkitTextFillColor:transparent]',
      '[backgroundClip:text]',
    );
  }

  return result.join(' ');
};

// 将 CSS 颜色值转换为 Tailwind 颜色名称
const convertCSSColorToTailwind = (cssColor: string): string => {
  // 移除空格并转为小写
  const color = cssColor.trim().toLowerCase();

  // 处理基础颜色
  if (color === '#ffffff' || color === '#fff' || color === 'white') return 'white';
  if (color === '#000000' || color === '#000' || color === 'black') return 'black';
  if (color === 'transparent') return 'transparent';
  if (color === 'currentcolor') return 'current';

  // 反向查找 Tailwind 颜色映射
  const colorMap: Record<string, Record<string, string>> = {
    blue: {
      '#eff6ff': '50',
      '#dbeafe': '100',
      '#bfdbfe': '200',
      '#93c5fd': '300',
      '#60a5fa': '400',
      '#3b82f6': '500',
      '#2563eb': '600',
      '#1d4ed8': '700',
      '#1e40af': '800',
      '#1e3a8a': '900',
      '#172554': '950',
    },
    indigo: {
      '#eef2ff': '50',
      '#e0e7ff': '100',
      '#c7d2fe': '200',
      '#a5b4fc': '300',
      '#818cf8': '400',
      '#6366f1': '500',
      '#4f46e5': '600',
      '#4338ca': '700',
      '#3730a3': '800',
      '#312e81': '900',
      '#1e1b4b': '950',
    },
    red: {
      '#fef2f2': '50',
      '#fee2e2': '100',
      '#fecaca': '200',
      '#fca5a5': '300',
      '#f87171': '400',
      '#ef4444': '500',
      '#dc2626': '600',
      '#b91c1c': '700',
      '#991b1b': '800',
      '#7f1d1d': '900',
      '#450a0a': '950',
    },
    green: {
      '#f0fdf4': '50',
      '#dcfce7': '100',
      '#bbf7d0': '200',
      '#86efac': '300',
      '#4ade80': '400',
      '#22c55e': '500',
      '#16a34a': '600',
      '#15803d': '700',
      '#166534': '800',
      '#14532d': '900',
      '#052e16': '950',
    },
    purple: {
      '#faf5ff': '50',
      '#f3e8ff': '100',
      '#e9d5ff': '200',
      '#d8b4fe': '300',
      '#c084fc': '400',
      '#a855f7': '500',
      '#9333ea': '600',
      '#7c3aed': '700',
      '#6b21a8': '800',
      '#581c87': '900',
      '#3b0764': '950',
    },
  };

  // 查找匹配的颜色
  for (const [colorName, shades] of Object.entries(colorMap)) {
    for (const [hex, shade] of Object.entries(shades)) {
      if (color === hex) {
        return `${colorName}-${shade}`;
      }
    }
  }

  // 如果找不到匹配，使用自定义格式
  return `[${cssColor}]`;
};

// 解析颜色停止点
const parseColorStops = (colorsStr: string): Array<{ color: string; position?: string }> => {
  const stops: Array<{ color: string; position?: string }> = [];

  // 使用更精确的正则来分割颜色停止点，正确处理 rgba() 中的逗号
  // 修复：使用更准确的正则表达式来匹配完整的 rgba() 值
  const colorStopRegex =
    /(?:rgba?\([^)]*\)|hsla?\([^)]*\)|#[0-9a-fA-F]{3,8}|[a-zA-Z]+)(?:\s+[\d.]+%?)?/g;

  // 先尝试用改进的方法解析
  let currentIndex = 0;
  const result: Array<{ color: string; position?: string }> = [];

  while (currentIndex < colorsStr.length) {
    // 跳过空白字符
    while (currentIndex < colorsStr.length && /\s/.test(colorsStr[currentIndex])) {
      currentIndex++;
    }

    if (currentIndex >= colorsStr.length) break;

    let colorEnd = currentIndex;
    let parenCount = 0;
    let inFunction = false;

    // 解析颜色值
    while (colorEnd < colorsStr.length) {
      const char = colorsStr[colorEnd];

      if (char === '(' && !inFunction) {
        inFunction = true;
        parenCount = 1;
      } else if (char === '(' && inFunction) {
        parenCount++;
      } else if (char === ')' && inFunction) {
        parenCount--;
        if (parenCount === 0) {
          colorEnd++;
          break;
        }
      } else if (!inFunction && (char === ',' || /\s/.test(char))) {
        // 如果不在函数内且遇到逗号或空格，检查是否是颜色结束
        if (char === ',') break;
        // 对于空格，需要检查后面是否是百分比或下一个颜色
        let nextNonSpace = colorEnd + 1;
        while (nextNonSpace < colorsStr.length && /\s/.test(colorsStr[nextNonSpace])) {
          nextNonSpace++;
        }
        if (nextNonSpace < colorsStr.length && /[\d.]/.test(colorsStr[nextNonSpace])) {
          // 后面是数字，可能是位置信息
          break;
        }
        if (
          nextNonSpace < colorsStr.length &&
          (colorsStr[nextNonSpace] === '#' ||
            colorsStr.substring(nextNonSpace).match(/^(rgba?|hsla?|[a-zA-Z]+)/))
        ) {
          // 后面是新的颜色
          break;
        }
      }

      colorEnd++;
    }

    const colorPart = colorsStr.substring(currentIndex, colorEnd).trim();
    if (!colorPart) break;

    // 解析位置信息
    currentIndex = colorEnd;
    while (currentIndex < colorsStr.length && /\s/.test(colorsStr[currentIndex])) {
      currentIndex++;
    }

    let position: string | undefined;
    if (currentIndex < colorsStr.length && /[\d.]/.test(colorsStr[currentIndex])) {
      let posEnd = currentIndex;
      while (posEnd < colorsStr.length && !/[,\s]/.test(colorsStr[posEnd])) {
        posEnd++;
      }
      position = colorsStr.substring(currentIndex, posEnd).trim();
      currentIndex = posEnd;
    }

    // 跳过逗号
    while (
      currentIndex < colorsStr.length &&
      (colorsStr[currentIndex] === ',' || /\s/.test(colorsStr[currentIndex]))
    ) {
      currentIndex++;
    }

    result.push({ color: colorPart, position });
  }

  // 如果解析结果为空，回退到原来的方法
  if (result.length === 0) {
    const matches = colorsStr.match(colorStopRegex);
    if (matches) {
      matches.forEach((match) => {
        const trimmed = match.trim();
        const parts = trimmed.split(/\s+/);
        const color = parts[0];
        const position = parts[1];
        result.push({ color, position });
      });
    }
  }

  return result;
};

// 将 Tailwind 颜色名称转换为 CSS 颜色值
const convertTailwindColorToCSS = (colorName: string): string => {
  // 处理基础颜色
  const basicColors: Record<string, string> = {
    white: '#ffffff',
    black: '#000000',
    transparent: 'transparent',
    current: 'currentColor',
  };

  if (basicColors[colorName]) {
    return basicColors[colorName];
  }

  // 处理带数字的颜色 (如 blue-500, red-900)
  const colorMatch = colorName.match(/^(\w+)-(\d+)$/);
  if (colorMatch) {
    const [, color, shade] = colorMatch;

    // Tailwind 标准颜色映射 (简化版本，包含常用颜色)
    const colorMap: Record<string, Record<string, string>> = {
      slate: {
        '50': '#f8fafc',
        '100': '#f1f5f9',
        '200': '#e2e8f0',
        '300': '#cbd5e1',
        '400': '#94a3b8',
        '500': '#64748b',
        '600': '#475569',
        '700': '#334155',
        '800': '#1e293b',
        '900': '#0f172a',
        '950': '#020617',
      },
      gray: {
        '50': '#f9fafb',
        '100': '#f3f4f6',
        '200': '#e5e7eb',
        '300': '#d1d5db',
        '400': '#9ca3af',
        '500': '#6b7280',
        '600': '#4b5563',
        '700': '#374151',
        '800': '#1f2937',
        '900': '#111827',
        '950': '#030712',
      },
      red: {
        '50': '#fef2f2',
        '100': '#fee2e2',
        '200': '#fecaca',
        '300': '#fca5a5',
        '400': '#f87171',
        '500': '#ef4444',
        '600': '#dc2626',
        '700': '#b91c1c',
        '800': '#991b1b',
        '900': '#7f1d1d',
        '950': '#450a0a',
      },
      orange: {
        '50': '#fff7ed',
        '100': '#ffedd5',
        '200': '#fed7aa',
        '300': '#fdba74',
        '400': '#fb923c',
        '500': '#f97316',
        '600': '#ea580c',
        '700': '#c2410c',
        '800': '#9a3412',
        '900': '#7c2d12',
        '950': '#431407',
      },
      yellow: {
        '50': '#fefce8',
        '100': '#fef3c7',
        '200': '#fde68a',
        '300': '#fcd34d',
        '400': '#fbbf24',
        '500': '#f59e0b',
        '600': '#d97706',
        '700': '#b45309',
        '800': '#92400e',
        '900': '#78350f',
        '950': '#451a03',
      },
      green: {
        '50': '#f0fdf4',
        '100': '#dcfce7',
        '200': '#bbf7d0',
        '300': '#86efac',
        '400': '#4ade80',
        '500': '#22c55e',
        '600': '#16a34a',
        '700': '#15803d',
        '800': '#166534',
        '900': '#14532d',
        '950': '#052e16',
      },
      blue: {
        '50': '#eff6ff',
        '100': '#dbeafe',
        '200': '#bfdbfe',
        '300': '#93c5fd',
        '400': '#60a5fa',
        '500': '#3b82f6',
        '600': '#2563eb',
        '700': '#1d4ed8',
        '800': '#1e40af',
        '900': '#1e3a8a',
        '950': '#172554',
      },
      indigo: {
        '50': '#eef2ff',
        '100': '#e0e7ff',
        '200': '#c7d2fe',
        '300': '#a5b4fc',
        '400': '#818cf8',
        '500': '#6366f1',
        '600': '#4f46e5',
        '700': '#4338ca',
        '800': '#3730a3',
        '900': '#312e81',
        '950': '#1e1b4b',
      },
      purple: {
        '50': '#faf5ff',
        '100': '#f3e8ff',
        '200': '#e9d5ff',
        '300': '#d8b4fe',
        '400': '#c084fc',
        '500': '#a855f7',
        '600': '#9333ea',
        '700': '#7c3aed',
        '800': '#6b21a8',
        '900': '#581c87',
        '950': '#3b0764',
      },
      pink: {
        '50': '#fdf2f8',
        '100': '#fce7f3',
        '200': '#fbcfe8',
        '300': '#f9a8d4',
        '400': '#f472b6',
        '500': '#ec4899',
        '600': '#db2777',
        '700': '#be185d',
        '800': '#9d174d',
        '900': '#831843',
        '950': '#500724',
      },
    };

    if (colorMap[color] && colorMap[color][shade]) {
      return colorMap[color][shade];
    }
  }

  // 如果找不到匹配的颜色，返回 CSS 变量格式
  return `var(--${colorName})`;
};

// 解析复杂的 transform 组合
const parseTransformCombination = (transformValue: string): string[] => {
  const transforms = transformValue.match(/(\w+)\([^)]+\)/g) || [];
  const tailwindClasses: string[] = [];

  transforms.forEach((transform) => {
    const match = transform.match(/(\w+)\(([^)]+)\)/);
    if (!match) return;

    const [, func, value] = match;
    const cleanValue = value.trim();

    switch (func) {
      case 'translateX':
        tailwindClasses.push(convertTranslateValue('x', cleanValue));
        break;
      case 'translateY':
        tailwindClasses.push(convertTranslateValue('y', cleanValue));
        break;
      case 'translateZ':
        tailwindClasses.push(`translate-z-[${cleanValue}]`);
        break;
      case 'translate':
        const [x, y] = cleanValue.split(',').map((v) => v.trim());
        tailwindClasses.push(convertTranslateValue('x', x));
        if (y) tailwindClasses.push(convertTranslateValue('y', y));
        break;
      case 'rotate':
        tailwindClasses.push(convertRotateValue(cleanValue));
        break;
      case 'rotateX':
        tailwindClasses.push(`rotate-x-[${cleanValue}]`);
        break;
      case 'rotateY':
        tailwindClasses.push(`rotate-y-[${cleanValue}]`);
        break;
      case 'rotateZ':
        tailwindClasses.push(convertRotateValue(cleanValue));
        break;
      case 'scale':
        tailwindClasses.push(convertScaleValue(cleanValue));
        break;
      case 'scaleX':
        tailwindClasses.push(`scale-x-[${cleanValue}]`);
        break;
      case 'scaleY':
        tailwindClasses.push(`scale-y-[${cleanValue}]`);
        break;
      case 'skew':
        const [skewX, skewY] = cleanValue.split(',').map((v) => v.trim());
        tailwindClasses.push(`skew-x-[${skewX}]`);
        if (skewY) tailwindClasses.push(`skew-y-[${skewY}]`);
        break;
      case 'skewX':
        tailwindClasses.push(`skew-x-[${cleanValue}]`);
        break;
      case 'skewY':
        tailwindClasses.push(`skew-y-[${cleanValue}]`);
        break;
      case 'perspective':
        tailwindClasses.push(`perspective-[${cleanValue}]`);
        break;
      default:
        // 未知的变换函数，使用自定义格式
        tailwindClasses.push(`[transform:${transform}]`);
    }
  });

  return tailwindClasses;
};

// 转换 translate 值
const convertTranslateValue = (axis: string, value: string): string => {
  // 标准值映射
  const standardValues: Record<string, string> = {
    '0px': '0',
    '1px': 'px',
    '2px': '0.5',
    '4px': '1',
    '8px': '2',
    '12px': '3',
    '16px': '4',
    '20px': '5',
    '24px': '6',
    '32px': '8',
    '50%': '1/2',
    '100%': 'full',
    '-50%': '-1/2',
    '-100%': '-full',
  };

  const standardValue = standardValues[value];
  if (standardValue) {
    return `translate-${axis}-${standardValue}`;
  }

  return `translate-${axis}-[${value}]`;
};

// 转换 rotate 值
const convertRotateValue = (value: string): string => {
  const standardRotations: Record<string, string> = {
    '0deg': '0',
    '1deg': '1',
    '2deg': '2',
    '3deg': '3',
    '6deg': '6',
    '12deg': '12',
    '45deg': '45',
    '90deg': '90',
    '180deg': '180',
    '-1deg': '-1',
    '-2deg': '-2',
    '-3deg': '-3',
    '-6deg': '-6',
    '-12deg': '-12',
    '-45deg': '-45',
    '-90deg': '-90',
    '-180deg': '-180',
  };

  const standardValue = standardRotations[value];
  if (standardValue) {
    return `rotate-${standardValue}`;
  }

  return `rotate-[${value}]`;
};

// 转换 scale 值
const convertScaleValue = (value: string): string => {
  const standardScales: Record<string, string> = {
    '0': '0',
    '0.5': '50',
    '0.75': '75',
    '0.9': '90',
    '0.95': '95',
    '1': '100',
    '1.05': '105',
    '1.1': '110',
    '1.25': '125',
    '1.5': '150',
    '2': '200',
  };

  const standardValue = standardScales[value];
  if (standardValue) {
    return `scale-${standardValue}`;
  }

  return `scale-[${value}]`;
};

// 转换持续时间为 Tailwind 类名
const convertDurationToTailwind = (duration: string): string | null => {
  const durationMap: Record<string, string> = {
    '75ms': 'duration-75',
    '100ms': 'duration-100',
    '150ms': 'duration-150',
    '200ms': 'duration-200',
    '300ms': 'duration-300',
    '500ms': 'duration-500',
    '700ms': 'duration-700',
    '1000ms': 'duration-1000',
    '0.075s': 'duration-75',
    '0.1s': 'duration-100',
    '0.15s': 'duration-150',
    '0.2s': 'duration-200',
    '0.3s': 'duration-300',
    '0.5s': 'duration-500',
    '0.7s': 'duration-700',
    '1s': 'duration-1000',
  };

  return durationMap[duration] || `duration-[${duration}]`;
};

// 转换时序函数为 Tailwind 类名
const convertEasingToTailwind = (easing: string): string | null => {
  const easingMap: Record<string, string> = {
    linear: 'ease-linear',
    ease: 'ease-in',
    'ease-in': 'ease-in',
    'ease-out': 'ease-out',
    'ease-in-out': 'ease-in-out',
    'cubic-bezier(0.4, 0, 0.2, 1)': 'ease-out',
    'cubic-bezier(0, 0, 0.2, 1)': 'ease-in-out',
    'cubic-bezier(0.4, 0, 1, 1)': 'ease-in',
    'cubic-bezier(0, 0, 1, 1)': 'ease-linear',
  };

  return easingMap[easing] || `ease-[${easing}]`;
};

// 智能冲突检测：分析伪类样式、响应式样式与基础样式的冲突
const analyzeStyleConflicts = (classNames: string[]) => {
  const pseudoClasses: string[] = [];
  const responsiveClasses: string[] = [];
  const baseClasses: string[] = [];
  const protectedClasses: Set<string> = new Set();

  // 分离伪类、响应式类和基础类
  classNames.forEach((className) => {
    if (className.includes(':')) {
      // 检查是否是响应式类
      if (/^(sm|md|lg|xl|2xl):/.test(className)) {
        responsiveClasses.push(className);
      } else {
        pseudoClasses.push(className);
      }
    } else {
      baseClasses.push(className);
    }
  });

  // 定义样式属性映射
  const stylePropertyMap = {
    // 背景相关
    background: ['bg-', 'bg-['],
    backgroundColor: ['bg-', 'bg-['],
    // 文本相关
    color: ['text-', 'text-['],
    // 边框相关
    borderColor: ['border-', 'border-['],
    borderWidth: ['border-', 'border-t-', 'border-r-', 'border-b-', 'border-l-'],
    // 阴影相关
    boxShadow: ['shadow-', 'shadow-['],
    // 透明度相关
    opacity: ['opacity-'],
    // 变换相关
    transform: ['scale-', 'rotate-', 'translate-', 'skew-'],
    // 尺寸相关
    width: ['w-', 'w-['],
    height: ['h-', 'h-['],
    // 内边距相关
    padding: ['p-', 'px-', 'py-', 'pt-', 'pr-', 'pb-', 'pl-', 'p-['],
    // 外边距相关
    margin: ['m-', 'mx-', 'my-', 'mt-', 'mr-', 'mb-', 'ml-', 'm-['],
    // Flexbox 相关
    display: ['flex', 'block', 'inline', 'inline-block', 'grid', 'hidden'],
    flexDirection: ['flex-row', 'flex-col', 'flex-row-reverse', 'flex-col-reverse'],
    justifyContent: [
      'justify-start',
      'justify-end',
      'justify-center',
      'justify-between',
      'justify-around',
      'justify-evenly',
    ],
    alignItems: ['items-start', 'items-end', 'items-center', 'items-baseline', 'items-stretch'],
    flexWrap: ['flex-wrap', 'flex-nowrap', 'flex-wrap-reverse'],
    flex: ['flex-1', 'flex-auto', 'flex-initial', 'flex-none'],
    // 定位相关
    position: ['relative', 'absolute', 'fixed', 'sticky', 'static'],
    top: ['top-', 'top-['],
    right: ['right-', 'right-['],
    bottom: ['bottom-', 'bottom-['],
    left: ['left-', 'left-['],
    zIndex: ['z-', 'z-['],
  };

  // 检测伪类与基础类的冲突
  pseudoClasses.forEach((pseudoClass) => {
    const [, ...classParts] = pseudoClass.split(':');
    const actualClass = classParts.join(':');

    // 找到伪类影响的样式属性
    for (const [, prefixes] of Object.entries(stylePropertyMap)) {
      const pseudoAffectsProperty = prefixes.some((prefix) => actualClass.startsWith(prefix));

      if (pseudoAffectsProperty) {
        // 查找基础类中是否有相同属性的样式
        baseClasses.forEach((baseClass) => {
          const baseAffectsProperty = prefixes.some((prefix) => baseClass.startsWith(prefix));
          if (baseAffectsProperty) {
            // 发现冲突，保护基础类不被转换为内联样式
            protectedClasses.add(baseClass);
          }
        });
      }
    }
  });

  // 检测响应式类与基础类的冲突
  responsiveClasses.forEach((responsiveClass) => {
    const [, ...classParts] = responsiveClass.split(':');
    const actualClass = classParts.join(':');

    // 找到响应式类影响的样式属性
    for (const [, prefixes] of Object.entries(stylePropertyMap)) {
      const responsiveAffectsProperty = prefixes.some(
        (prefix) => actualClass.startsWith(prefix) || prefixes.includes(actualClass),
      );

      if (responsiveAffectsProperty) {
        // 查找基础类中是否有相同属性的样式
        baseClasses.forEach((baseClass) => {
          const baseAffectsProperty = prefixes.some(
            (prefix) => baseClass.startsWith(prefix) || prefixes.includes(baseClass),
          );
          if (baseAffectsProperty) {
            // 发现冲突，保护基础类不被转换为内联样式
            protectedClasses.add(baseClass);
          }
        });
      }
    }
  });

  return {
    pseudoClasses,
    responsiveClasses,
    baseClasses,
    protectedClasses,
    conflicts: protectedClasses.size > 0,
  };
};

// 解析渐变相关的 Tailwind 类名
const parseGradientClasses = (classNames: string[]) => {
  let direction: string | undefined;
  const colors: Array<{ color: string; position?: string; type: 'from' | 'via' | 'to' }> = [];
  const gradientClassNames: string[] = [];
  let isTextGradient = false;

  // 检查是否是文本渐变
  if (classNames.includes('bg-clip-text') && classNames.includes('text-transparent')) {
    isTextGradient = true;
    gradientClassNames.push('bg-clip-text', 'text-transparent');
  }

  classNames.forEach((className) => {
    // 解析方向
    if (className.startsWith('bg-gradient-to-')) {
      direction = className.replace('bg-gradient-to-', '');
      gradientClassNames.push(className);
      return;
    }

    // 解析 from 颜色 - 自定义格式
    const fromCustomMatch = className.match(/^from-\[(.+)\]$/);
    if (fromCustomMatch) {
      colors.push({ color: fromCustomMatch[1], type: 'from' });
      gradientClassNames.push(className);
      return;
    }

    // 解析 from 颜色 - 标准格式 (如 from-blue-900)
    const fromStandardMatch = className.match(/^from-(.+)$/);
    if (fromStandardMatch && !fromStandardMatch[1].startsWith('[')) {
      const colorName = fromStandardMatch[1];
      colors.push({ color: convertTailwindColorToCSS(colorName), type: 'from' });
      gradientClassNames.push(className);
      return;
    }

    // 解析 via 颜色 - 自定义格式
    const viaCustomMatch = className.match(/^via-\[(.+)\]$/);
    if (viaCustomMatch) {
      colors.push({ color: viaCustomMatch[1], type: 'via' });
      gradientClassNames.push(className);
      return;
    }

    // 解析 via 颜色 - 标准格式 (如 via-purple-500)
    const viaStandardMatch = className.match(/^via-(.+)$/);
    if (viaStandardMatch && !viaStandardMatch[1].startsWith('[')) {
      const colorName = viaStandardMatch[1];
      colors.push({ color: convertTailwindColorToCSS(colorName), type: 'via' });
      gradientClassNames.push(className);
      return;
    }

    // 解析 to 颜色 - 自定义格式
    const toCustomMatch = className.match(/^to-\[(.+)\]$/);
    if (toCustomMatch) {
      colors.push({ color: toCustomMatch[1], type: 'to' });
      gradientClassNames.push(className);
      return;
    }

    // 解析 to 颜色 - 标准格式 (如 to-indigo-800)
    const toStandardMatch = className.match(/^to-(.+)$/);
    if (toStandardMatch && !toStandardMatch[1].startsWith('[')) {
      const colorName = toStandardMatch[1];
      colors.push({ color: convertTailwindColorToCSS(colorName), type: 'to' });
      gradientClassNames.push(className);
      return;
    }

    // 解析带位置的颜色停止点（扩展支持）
    const colorStopMatch = className.match(/^(from|via|to)-\[(.+)\s+([\d.]+%?)\]$/);
    if (colorStopMatch) {
      const [, type, color, position] = colorStopMatch;
      colors.push({
        color,
        position,
        type: type as 'from' | 'via' | 'to',
      });
      gradientClassNames.push(className);
      return;
    }
  });

  // 按类型排序颜色：from -> via -> to
  colors.sort((a, b) => {
    const order = { from: 0, via: 1, to: 2 };
    return order[a.type] - order[b.type];
  });

  return {
    isValid: direction && colors.length >= 2,
    direction,
    colors,
    isTextGradient,
    classNames: gradientClassNames,
  };
};

// 解析复杂渐变（径向渐变、锥形渐变）与颜色组合
const parseComplexGradientWithColors = (classNames: string[]) => {
  let baseGradient: string | undefined;
  const colors: Array<{ color: string; position?: string; type: 'from' | 'via' | 'to' }> = [];
  const complexGradientClassNames: string[] = [];
  let isTextGradient = false;

  // 检查是否是文本渐变
  if (classNames.includes('bg-clip-text') && classNames.includes('text-transparent')) {
    isTextGradient = true;
    complexGradientClassNames.push('bg-clip-text', 'text-transparent');
  }

  classNames.forEach((className) => {
    // 查找包含 var(--tw-gradient-stops) 的复杂渐变
    if (className.startsWith('bg-[') && className.includes('var(--tw-gradient-stops)')) {
      const gradientMatch = className.match(/bg-\[(.+)\]$/);
      if (gradientMatch) {
        baseGradient = gradientMatch[1];
        complexGradientClassNames.push(className);
        return;
      }
    }

    // 解析颜色（复用之前的逻辑）
    const fromStandardMatch = className.match(/^from-(.+)$/);
    if (fromStandardMatch && !fromStandardMatch[1].startsWith('[')) {
      const colorName = fromStandardMatch[1];
      colors.push({ color: convertTailwindColorToCSS(colorName), type: 'from' });
      complexGradientClassNames.push(className);
      return;
    }

    const fromCustomMatch = className.match(/^from-\[(.+)\]$/);
    if (fromCustomMatch) {
      colors.push({ color: fromCustomMatch[1], type: 'from' });
      complexGradientClassNames.push(className);
      return;
    }

    const viaStandardMatch = className.match(/^via-(.+)$/);
    if (viaStandardMatch && !viaStandardMatch[1].startsWith('[')) {
      const colorName = viaStandardMatch[1];
      colors.push({ color: convertTailwindColorToCSS(colorName), type: 'via' });
      complexGradientClassNames.push(className);
      return;
    }

    const viaCustomMatch = className.match(/^via-\[(.+)\]$/);
    if (viaCustomMatch) {
      colors.push({ color: viaCustomMatch[1], type: 'via' });
      complexGradientClassNames.push(className);
      return;
    }

    const toStandardMatch = className.match(/^to-(.+)$/);
    if (toStandardMatch && !toStandardMatch[1].startsWith('[')) {
      const colorName = toStandardMatch[1];
      colors.push({ color: convertTailwindColorToCSS(colorName), type: 'to' });
      complexGradientClassNames.push(className);
      return;
    }

    const toCustomMatch = className.match(/^to-\[(.+)\]$/);
    if (toCustomMatch) {
      colors.push({ color: toCustomMatch[1], type: 'to' });
      complexGradientClassNames.push(className);
      return;
    }
  });

  // 按类型排序颜色：from -> via -> to
  colors.sort((a, b) => {
    const order = { from: 0, via: 1, to: 2 };
    return order[a.type] - order[b.type];
  });

  return {
    isValid: baseGradient && colors.length >= 2,
    baseGradient,
    colors,
    isTextGradient,
    classNames: complexGradientClassNames,
  };
};

type StyleTransformerType = typeof StyleTransformer;

interface InlineStyleResult {
  style?: Record<string, string>;
  convertedClasses: string[];
  unconvertedClasses: string[];
  errors?: string[];
}

interface IEnhancedStyleTransformer extends StyleTransformerType {
  // 双向转换能力
  toInlineStyle: (classNames: string[]) => InlineStyleResult;
  // 预设样式转换
  getPresetStyle: (preset: string) => string;
  // 合并多个样式对象并转换为 Tailwind 类名
  mergeClassesToStyle: (styles: string[]) => string;
}

// 处理视口单位
const handleViewportUnit = (value: string, prefix: 'h' | 'w'): string => {
  const numValue = parseFloat(value);
  if (isNaN(numValue)) return `${prefix}-auto`;

  // 处理常见的预设值
  const presetMap: Record<number, string> = {
    25: `${prefix}-1/4`,
    50: `${prefix}-1/2`,
    75: `${prefix}-3/4`,
    100: `${prefix}-full`,
  };

  // 如果是视口单位（vh/vw），使用 screen 或自定义值
  if (value.endsWith('vh') || value.endsWith('vw')) {
    if (numValue === 100) {
      return `${prefix}-screen`;
    }
    return `${prefix}-[${numValue}${value.endsWith('vh') ? 'vh' : 'vw'}]`;
  }

  // 处理百分比
  if (presetMap[numValue]) {
    return presetMap[numValue];
  }

  // 对于自定义百分比值，使用方括号语法
  return `${prefix}-[${numValue}%]`;
};

// 扩展原有的样式映射
const enhancedStyleToTailwind = {
  // 继承原有的基础映射
  color: (value: string, styleObj?: Record<string, any>) => {
    // 如果是CSS变量，直接使用中括号语法
    if (value.startsWith('var(--')) {
      return `text-[${value}]`;
    }
    return `text-${toTailwindColor(value)}`;
  },
  backgroundColor: (value: string, styleObj?: Record<string, any>) => {
    // 如果是CSS变量，直接使用中括号语法
    if (value.startsWith('var(--')) {
      return `bg-[${value}]`;
    }
    // 处理带空格的CSS变量值
    if (value.includes(' ') && value.startsWith('var(--')) {
      return `bg-[${value}]`;
    }
    return `bg-${toTailwindColor(value)}`;
  },
  background: (value: string, styleObj?: Record<string, any>) => {
    // 检查是否是文本渐变（需要同时检查多个条件）
    const isTextGradient =
      styleObj &&
      (styleObj.backgroundClip === 'text' || styleObj.WebkitBackgroundClip === 'text') &&
      (styleObj.color === 'transparent' || styleObj.WebkitTextFillColor === 'transparent');

    // 处理线性渐变
    if (value.startsWith('linear-gradient(')) {
      return parseLinearGradientToTailwindWithStandardColors(value, !!isTextGradient);
    }

    // 处理rgba颜色格式（支持空格分隔和逗号分隔）
    if (value.includes('rgba(')) {
      // 标准化rgba格式（将空格替换为逗号）
      const normalizedValue = value.replace(
        /rgba\((\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\)/,
        'rgba($1, $2, $3, $4)',
      );
      return `bg-[${normalizedValue}]`;
    }

    // 默认处理
    return `bg-[${value}]`;
  },
  fontSize: (value: string) => {
    // 处理特殊值
    if (value === 'inherit') return 'text-inherit';
    if (value === 'unset') return 'text-unset';

    // 处理预设值映射
    const sizeMap: Record<string, string> = {
      '12px': 'text-xs',
      '14px': 'text-sm',
      '16px': 'text-base',
      '18px': 'text-lg',
      '20px': 'text-xl',
      '24px': 'text-2xl',
      '30px': 'text-3xl',
      '36px': 'text-4xl',
      '48px': 'text-5xl',
      '60px': 'text-6xl',
    };
    if (sizeMap[value]) return sizeMap[value];

    // 处理自定义值
    if (value.includes('px')) {
      return `text-[${value}]`;
    }

    // 默认处理
    return `text-[${value}]`;
  },
  padding: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `p-[${value}]`;
    }
    return value.endsWith('px') ? `p-[${value}]` : `p-${pxToUnit(value)}`;
  },
  paddingLeft: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `pl-[${value}]`;
    }
    return value.endsWith('px') ? `pl-[${value}]` : `pl-${pxToUnit(value)}`;
  },
  paddingRight: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `pr-[${value}]`;
    }
    return value.endsWith('px') ? `pr-[${value}]` : `pr-${pxToUnit(value)}`;
  },
  paddingTop: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `pt-[${value}]`;
    }
    return value.endsWith('px') ? `pt-[${value}]` : `pt-${pxToUnit(value)}`;
  },
  paddingBottom: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `pb-[${value}]`;
    }
    return value.endsWith('px') ? `pb-[${value}]` : `pb-${pxToUnit(value)}`;
  },
  overflow: (value: string) => `overflow-${value}`,
  overflowX: (value: string) => `overflow-x-${value}`,
  overflowY: (value: string) => `overflow-y-${value}`,
  margin: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `m-[${value}]`;
    }
    return value.endsWith('px') ? `m-[${value}]` : `m-${pxToUnit(value)}`;
  },
  marginLeft: (value: string) => {
    if (typeof value === 'number') {
      return `ml-[${value}]`;
    }
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `ml-[${value}]`;
    }
    return value.endsWith('px') ? `ml-[${value}]` : `ml-${pxToUnit(value)}`;
  },
  marginRight: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `mr-[${value}]`;
    }
    return value.endsWith('px') ? `mr-[${value}]` : `mr-${pxToUnit(value)}`;
  },
  marginTop: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `mt-[${value}]`;
    }
    return value.endsWith('px') ? `mt-[${value}]` : `mt-${pxToUnit(value)}`;
  },
  marginBottom: (value: string) => {
    // 处理百分比和其他非px单位
    if (value.includes('%') || (value.match(/[a-z]+$/) && !value.endsWith('px'))) {
      return `mb-[${value}]`;
    }
    return value.endsWith('px') ? `mb-[${value}]` : `mb-${pxToUnit(value)}`;
  },
  height: (value: string) => {
    if (value === '100vh') return 'h-screen';
    if (value.endsWith('vh')) {
      return `h-[${value}]`;
    }
    if (value === 'auto') return 'h-auto';
    if (value === '100%') return 'h-full';
    // 使用中括号语法处理所有自定义尺寸，包括px、%、em、rem等
    if (value.match(/[0-9]+(px|%|em|rem|vh|vw|vmin|vmax)/) || value.includes('calc')) {
      return `h-[${value}]`;
    }
    // 只有纯数字值才使用标准的Tailwind尺寸
    if (!isNaN(Number(value))) {
      return `h-${pxToUnit(value)}`;
    }
    // 其他情况也使用中括号
    return `h-[${value}]`;
  },
  width: (value: string) => {
    if (value.endsWith('vw')) {
      return handleViewportUnit(value.replace('vw', ''), 'w');
    }
    if (value === 'auto') return 'w-auto';
    if (value === '100vw') return 'w-screen';
    if (value === '100%') return 'w-full';
    // 使用中括号语法处理所有自定义尺寸，包括px、%、em、rem等
    if (value.match(/[0-9]+(px|%|em|rem|vh|vw|vmin|vmax)/) || value.includes('calc')) {
      return `w-[${value}]`;
    }
    // 只有纯数字值才使用标准的Tailwind尺寸
    if (!isNaN(Number(value))) {
      return `w-${pxToUnit(value)}`;
    }
    // 其他情况也使用中括号
    return `w-[${value}]`;
  },
  flexWrap: (value: string) => (value === 'wrap' ? 'flex-wrap' : 'flex-nowrap'),
  display: (value: string) => {
    const displayMap: Record<string, string> = {
      grid: 'grid',
      flex: 'flex',
      block: 'block',
      inline: 'inline',
      'inline-block': 'inline-block',
      'inline-flex': 'inline-flex',
      none: 'hidden',
    };
    return displayMap[value] || `[display:${value}]`;
  },
  flex: (value: string) => {
    const flexMap: Record<string, string> = {
      '1': 'flex-1',
      '2': 'flex-2',
      '3': 'flex-3',
      auto: 'flex-auto',
      initial: 'flex-initial',
      none: 'flex-none',
      grow: 'flex-grow',
      'grow-0': 'flex-grow-0',
      shrink: 'flex-shrink',
      'shrink-0': 'flex-shrink-0',
      basis: 'flex-basis',
      'basis-auto': 'flex-basis-auto',
      'basis-full': 'flex-basis-full',
      'basis-1/2': 'flex-basis-1/2',
      'basis-1/3': 'flex-basis-1/3',
      'basis-2/3': 'flex-basis-2/3',
      'basis-1/4': 'flex-basis-1/4',
      'basis-3/4': 'flex-basis-3/4',
    };
    return flexMap[value] || `flex-[${value}]`;
  },
  flexGrow: (value: string) => `flex-grow-${value}`,
  flexShrink: (value: string) => `flex-shrink-${value}`,
  flexBasis: (value: string) => `flex-basis-${value}`,
  flexDirection: (value: string) => (value === 'column' ? 'flex-col' : 'flex-row'),
  justifyContent: (value: string) => {
    const justifyMap: Record<string, string> = {
      'flex-start': 'justify-start',
      'flex-end': 'justify-end',
      center: 'justify-center',
      'space-between': 'justify-between',
      'space-around': 'justify-around',
    };
    return justifyMap[value] || `justify-${value}`;
  },
  alignItems: (value: string) => {
    const alignMap: Record<string, string> = {
      'flex-start': 'items-start',
      'flex-end': 'items-end',
      center: 'items-center',
      stretch: 'items-stretch',
      baseline: 'items-baseline',
    };
    return alignMap[value] || `items-${value}`;
  },
  // 添加边框相关的样式转换
  borderRadius: (value: string) => {
    // 处理特殊值
    if (value === '0px' || value === '0') return 'rounded-none';
    if (value === '9999px') return 'rounded-full';

    // 处理预设值映射
    const radiusMap: Record<string, string> = {
      '2px': 'rounded-sm',
      '4px': 'rounded',
      '6px': 'rounded-md',
      '8px': 'rounded-lg',
      '12px': 'rounded-xl',
      '16px': 'rounded-2xl',
      '24px': 'rounded-3xl',
    };
    if (radiusMap[value]) return radiusMap[value];

    // 处理自定义值
    if (value.includes('px')) {
      return `rounded-[${value}]`;
    }

    // 默认处理
    return `rounded-[${value}]`;
  },
  // 添加方向性圆角支持
  borderTopLeftRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-tl-none';
    if (value === '9999px') return 'rounded-tl-full';
    return `rounded-tl-[${value}]`;
  },
  borderTopRightRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-tr-none';
    if (value === '9999px') return 'rounded-tr-full';
    return `rounded-tr-[${value}]`;
  },
  borderBottomLeftRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-bl-none';
    if (value === '9999px') return 'rounded-bl-full';
    return `rounded-bl-[${value}]`;
  },
  borderBottomRightRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-br-none';
    if (value === '9999px') return 'rounded-br-full';
    return `rounded-br-[${value}]`;
  },
  borderTopRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-t-none';
    if (value === '9999px') return 'rounded-t-full';
    return `rounded-t-[${value}]`;
  },
  borderRightRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-r-none';
    if (value === '9999px') return 'rounded-r-full';
    return `rounded-r-[${value}]`;
  },
  borderBottomRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-b-none';
    if (value === '9999px') return 'rounded-b-full';
    return `rounded-b-[${value}]`;
  },
  borderLeftRadius: (value: string) => {
    if (value === '0px' || value === '0') return 'rounded-l-none';
    if (value === '9999px') return 'rounded-l-full';
    return `rounded-l-[${value}]`;
  },
  borderWidth: (value: string) => {
    const width = value.replace('px', '');
    return width === '1' ? 'border' : `border-[${value}]`;
  },
  borderStyle: (value: string) => {
    const styleMap: Record<string, string> = {
      solid: 'border-solid',
      dashed: 'border-dashed',
      dotted: 'border-dotted',
      double: 'border-double',
      none: 'border-none',
    };
    // 确保 value 是字符串类型，并且不会被错误地处理为变量
    const normalizedValue = String(value).toLowerCase();
    return styleMap[normalizedValue] || `border-${normalizedValue}`;
  },
  borderColor: (value: string) => {
    // 如果是CSS变量，直接使用中括号语法
    if (value.startsWith('var(--')) {
      return `border-[${value}]`;
    }

    // 处理特殊的边框值，如 "1px solid #ccc"
    const colorRegex = /^#([0-9a-f]{3}|[0-9a-f]{6})$|^rgb\(.*\)$|^rgba\(.*\)$/i;

    if (colorRegex.test(value)) {
      // 如果只是一个颜色值
      return `border-${toTailwindColor(value)}`;
    }

    return `border-[${value}]`;
  },
  border: (value: string) => {
    // 使用正则表达式匹配边框值，同时保留 rgba 中的空格
    const borderMatch = value.match(
      /^(\d+px|thin|medium|thick)\s+(solid|dashed|dotted|double|none)\s+(.+)$/,
    );

    if (borderMatch) {
      const [, width, style, color] = borderMatch;
      const widthClass = enhancedStyleToTailwind.borderWidth(width);
      const styleClass = enhancedStyleToTailwind.borderStyle(style);
      const colorClass = enhancedStyleToTailwind.borderColor(color);
      return [widthClass, styleClass, colorClass].filter(Boolean).join(' ');
    }

    // 如果无法匹配完整格式，尝试只匹配宽度和颜色
    const simpleMatch = value.match(/^(\d+px|thin|medium|thick)\s+(.+)$/);
    if (simpleMatch) {
      const [, width, color] = simpleMatch;
      const widthClass = enhancedStyleToTailwind.borderWidth(width);
      const colorClass = enhancedStyleToTailwind.borderColor(color);
      return [widthClass, 'border-solid', colorClass].filter(Boolean).join(' ');
    }

    // 如果只提供了颜色值
    if (value.startsWith('rgba') || value.startsWith('rgb') || value.startsWith('#')) {
      return enhancedStyleToTailwind.borderColor(value);
    }

    // 默认返回基本边框
    return 'border';
  },
  // 添加边框方向相关的样式转换
  borderTopWidth: (value: string) => {
    const width = value.replace('px', '');
    return width === '1' ? 'border-t' : `border-t-[${value}]`;
  },
  borderRightWidth: (value: string) => {
    const width = value.replace('px', '');
    return width === '1' ? 'border-r' : `border-r-[${value}]`;
  },
  borderBottomWidth: (value: string) => {
    if (/^\d+px$/.test(value)) {
      return `border-b-[${value}]`;
    }
    return value === '1' ? 'border-b' : `border-b-[${value}]`;
  },
  borderLeftWidth: (value: string) => {
    const width = value.replace('px', '');
    return width === '1' ? 'border-l' : `border-l-[${value}]`;
  },
  borderTopColor: (value: string) => {
    // 如果是CSS变量，直接使用中括号语法
    if (value.startsWith('var(--')) {
      return `border-t-[${value}]`;
    }
    return `border-t-${toTailwindColor(value)}`;
  },
  borderRightColor: (value: string) => {
    // 如果是CSS变量，直接使用中括号语法
    if (value.startsWith('var(--')) {
      return `border-r-[${value}]`;
    }
    return `border-r-${toTailwindColor(value)}`;
  },
  borderBottomColor: (value: string) => {
    // 如果是CSS变量，直接使用中括号语法
    if (value.startsWith('var(--')) {
      return `border-b-[${value}]`;
    }
    return `border-b-${toTailwindColor(value)}`;
  },
  borderLeftColor: (value: string) => {
    // 如果是CSS变量，直接使用中括号语法
    if (value.startsWith('var(--')) {
      return `border-l-[${value}]`;
    }
    return `border-l-${toTailwindColor(value)}`;
  },
  borderTopStyle: (value: string) => {
    const styleMap: Record<string, string> = {
      solid: 'border-t-solid',
      dashed: 'border-t-dashed',
      dotted: 'border-t-dotted',
      double: 'border-t-double',
      none: 'border-t-none',
    };
    const normalizedValue = String(value).toLowerCase();
    return styleMap[normalizedValue] || `border-t-${normalizedValue}`;
  },
  borderRightStyle: (value: string) => {
    const styleMap: Record<string, string> = {
      solid: 'border-r-solid',
      dashed: 'border-r-dashed',
      dotted: 'border-r-dotted',
      double: 'border-r-double',
      none: 'border-r-none',
    };
    const normalizedValue = String(value).toLowerCase();
    return styleMap[normalizedValue] || `border-r-${normalizedValue}`;
  },
  borderBottomStyle: (value: string) => {
    const styleMap: Record<string, string> = {
      solid: 'border-b-solid',
      dashed: 'border-b-dashed',
      dotted: 'border-b-dotted',
      double: 'border-b-double',
      none: 'border-b-none',
    };
    return styleMap[value.toLowerCase()] || `border-b-${value.toLowerCase()}`;
  },
  borderLeftStyle: (value: string) => {
    const styleMap: Record<string, string> = {
      solid: 'border-l-solid',
      dashed: 'border-l-dashed',
      dotted: 'border-l-dotted',
      double: 'border-l-double',
      none: 'border-l-none',
    };
    const normalizedValue = String(value).toLowerCase();
    return styleMap[normalizedValue] || `border-l-${normalizedValue}`;
  },
  // 添加 WebKit 相关属性支持
  WebkitBackgroundClip: (value: string) => {
    if (value === 'text') return '[WebkitBackgroundClip:text]';
    return `[WebkitBackgroundClip:${value}]`;
  },
  WebkitTextFillColor: (value: string) => {
    if (value === 'transparent') return '[WebkitTextFillColor:transparent]';
    return `[WebkitTextFillColor:${value}]`;
  },
  backgroundClip: (value: string) => {
    if (value === 'text') return '[backgroundClip:text]';
    return `[backgroundClip:${value}]`;
  },
  textOverflow: (value: string) => {
    if (value === 'ellipsis') return '[textOverflow:ellipsis]';
    return `[textOverflow:${value}]`;
  },
  whiteSpace: (value: string) => {
    if (value === 'nowrap') return '[whiteSpace:nowrap]';
    return `[whiteSpace:${value}]`;
  },
  lineHeight: (value: string) => {
    if (value === 'initial') return '[lineHeight:initial]';
    return `[lineHeight:${value}]`;
  },
  // 添加更多样式映射...
  maxWidth: (value: string) => {
    if (value === '100%') return 'max-w-full';
    if (value === '100vw') return 'max-w-screen';
    if (value.endsWith('px')) return `max-w-[${value}]`;
    return `max-w-${pxToUnit(value)}`;
  },
  maxHeight: (value: string) => {
    if (value === '100%') return 'max-h-full';
    if (value === '100vh') return 'max-h-screen';
    if (value.endsWith('px')) return `max-h-[${value}]`;
    return `max-h-${pxToUnit(value)}`;
  },
  minWidth: (value: string) => {
    if (value === '100%') return 'min-w-full';
    if (value === '100vw') return 'min-w-screen';
    if (value.endsWith('px')) return `min-w-[${value}]`;
    return `min-w-${pxToUnit(value)}`;
  },
  minHeight: (value: string) => {
    if (value === '100%') return 'min-h-full';
    if (value === '100vh') return 'min-h-screen';
    if (value.endsWith('px')) return `min-h-[${value}]`;
    return `min-h-${pxToUnit(value)}`;
  },
  fontWeight: (value: string) => {
    const weightMap: Record<string, string> = {
      '100': 'font-thin',
      '200': 'font-extralight',
      '300': 'font-light',
      '400': 'font-normal',
      '500': 'font-medium',
      '600': 'font-semibold',
      '700': 'font-bold',
      '800': 'font-extrabold',
      '900': 'font-black',
      normal: 'font-normal',
      bold: 'font-bold',
    };
    return weightMap[value] || `font-[${value}]`;
  },
  boxShadow: (value: string) => {
    const shadowMap: Record<string, string> = {
      sm: 'shadow-sm',
      md: 'shadow-md',
      lg: 'shadow-lg',
      xl: 'shadow-xl',
      '2xl': 'shadow-2xl',
      inner: 'shadow-inner',
      none: 'shadow-none',
    };
    return shadowMap[value] || `shadow-[${value}]`;
  },
  position: (value: string) => {
    return value;
  },
  // 添加 top, right, bottom, left 属性转换
  top: (value: string) => {
    if (value === '0') return 'top-0';
    if (value === 'auto') return 'top-auto';
    // 处理百分比和其他单位
    return `top-[${value}]`;
  },
  right: (value: string) => {
    if (value === '0') return 'right-0';
    if (value === 'auto') return 'right-auto';
    return `right-[${value}]`;
  },
  bottom: (value: string) => {
    if (value === '0') return 'bottom-0';
    if (value === 'auto') return 'bottom-auto';
    return `bottom-[${value}]`;
  },
  left: (value: string) => {
    if (value === '0') return 'left-0';
    if (value === 'auto') return 'left-auto';
    return `left-[${value}]`;
  },
  // 添加 z-index 属性转换
  zIndex: (value: string | number) => {
    const strValue = typeof value === 'number' ? value.toString() : value;
    const zIndexMap: Record<string, string> = {
      '0': 'z-0',
      '10': 'z-10',
      '20': 'z-20',
      '30': 'z-30',
      '40': 'z-40',
      '50': 'z-50',
      auto: 'z-auto',
    };

    // 处理已经带有中括号的值（如z-[-1]）
    if (strValue.startsWith('[') && strValue.endsWith(']')) {
      return `z-${strValue}`;
    }

    // 处理负值，使用中括号语法
    if (strValue.startsWith('-')) {
      return `z-[${strValue}]`;
    }

    // 处理预设值或使用中括号语法
    return zIndexMap[strValue] || `z-[${strValue}]`;
  },
  // 添加背景相关的样式转换
  backgroundImage: (value: string) => {
    if (value.startsWith('url(')) {
      return `bg-[${value}]`;
    }
    if (value.startsWith('linear-gradient') || value.startsWith('radial-gradient')) {
      return `bg-gradient-to-r bg-[${value}]`;
    }
    return `bg-[${value}]`;
  },
  backgroundRepeat: (value: string) => {
    const repeatMap: Record<string, string> = {
      'no-repeat': 'bg-no-repeat',
      repeat: 'bg-repeat',
      'repeat-x': 'bg-repeat-x',
      'repeat-y': 'bg-repeat-y',
      round: 'bg-repeat-round',
      space: 'bg-repeat-space',
    };
    return repeatMap[value] || `bg-[repeat:${value}]`;
  },
  backgroundSize: (value: string) => {
    const sizeMap: Record<string, string> = {
      auto: 'bg-auto',
      cover: 'bg-cover',
      contain: 'bg-contain',
    };
    return sizeMap[value] || `bg-[length:${value}]`;
  },
  backgroundPosition: (value: string) => {
    const positionMap: Record<string, string> = {
      center: 'bg-center',
      top: 'bg-top',
      bottom: 'bg-bottom',
      left: 'bg-left',
      right: 'bg-right',
      'left top': 'bg-left-top',
      'right top': 'bg-right-top',
      'left bottom': 'bg-left-bottom',
      'right bottom': 'bg-right-bottom',
    };
    return positionMap[value] || `bg-[position:${value}]`;
  },
  // 添加文本阴影
  textShadow: (value: string) => {
    const shadowMap: Record<string, string> = {
      none: 'text-shadow-none',
      '0 1px 3px rgba(0,0,0,0.1)': 'text-shadow-sm',
      '0 2px 4px rgba(0,0,0,0.1)': 'text-shadow',
      '0 4px 8px rgba(0,0,0,0.1)': 'text-shadow-md',
      '0 8px 16px rgba(0,0,0,0.1)': 'text-shadow-lg',
      '0 12px 24px rgba(0,0,0,0.1)': 'text-shadow-xl',
      '0 16px 32px rgba(0,0,0,0.1)': 'text-shadow-2xl',
    };
    return shadowMap[value] || `text-shadow-[${value}]`;
  },
  gridTemplateColumns: (value: string) => {
    // 处理 repeat 格式
    const repeatMatch = value.match(/repeat\((\d+),\s*minmax\(0,\s*1fr\)\)/);
    if (repeatMatch) {
      return `grid-cols-${repeatMatch[1]}`;
    }

    // 处理复杂的自定义格式，需要将空格替换为下划线以符合 Tailwind 语法
    const normalizedValue = value.replace(/\s+/g, '_');
    return `grid-cols-[${normalizedValue}]`;
  },
  gridTemplateRows: (value: string) => {
    // 处理 repeat 格式
    const repeatMatch = value.match(/repeat\((\d+),\s*minmax\(0,\s*1fr\)\)/);
    if (repeatMatch) {
      return `grid-rows-${repeatMatch[1]}`;
    }

    // 处理复杂的自定义格式，需要将空格替换为下划线以符合 Tailwind 语法
    const normalizedValue = value.replace(/\s+/g, '_');
    return `grid-rows-[${normalizedValue}]`;
  },
  gap: (value: string) => {
    // 处理 gap-x 和 gap-y
    if (value.includes(' ')) {
      const [x, y] = value.split(' ');
      // 对每个值进行标准化处理
      const xClass = x.endsWith('px') ? `gap-x-${pxToUnit(x)}` : `gap-x-[${x}]`;
      const yClass = y.endsWith('px') ? `gap-y-${pxToUnit(y)}` : `gap-y-[${y}]`;
      return `${xClass} ${yClass}`;
    }

    // 处理单个 gap 值
    if (value.endsWith('px')) {
      const unit = pxToUnit(value);
      // 检查是否是标准的 Tailwind 单位
      const standardUnits = [
        '0',
        '0.5',
        '1',
        '1.5',
        '2',
        '2.5',
        '3',
        '3.5',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        '10',
        '11',
        '12',
        '14',
        '16',
        '20',
        '24',
        '28',
        '32',
        '36',
        '40',
        '44',
        '48',
        '52',
        '56',
        '60',
        '64',
        '72',
        '80',
        '96',
      ];
      if (standardUnits.includes(unit)) {
        return `gap-${unit}`;
      }
    }

    // 对于非标准值，使用自定义格式
    return `gap-[${value}]`;
  },
  cursor: (value: string) => {
    const cursorMap: Record<string, string> = {
      pointer: 'cursor-pointer',
      default: 'cursor-default',
      wait: 'cursor-wait',
      text: 'cursor-text',
      move: 'cursor-move',
      'not-allowed': 'cursor-not-allowed',
    };
    return cursorMap[value] || `cursor-[${value}]`;
  },
  letterSpacing: (value: string) => {
    // 处理特殊值
    if (value === 'normal') return 'tracking-normal';
    if (value === 'inherit') return 'tracking-inherit';
    if (value === 'unset') return 'tracking-unset';

    // 处理预设值映射
    const spacingMap: Record<string, string> = {
      '-2px': 'tracking-tighter',
      '-1px': 'tracking-tight',
      '0px': 'tracking-normal',
      '1px': 'tracking-wide',
      '2px': 'tracking-wider',
      '4px': 'tracking-widest',
    };
    if (spacingMap[value]) return spacingMap[value];

    // 处理自定义值
    if (value.includes('px')) {
      return `tracking-[${value}]`;
    }

    // 默认处理
    return `tracking-[${value}]`;
  },
  transform: (value: string) => {
    if (value === 'none') return 'transform-none';

    // 使用新的组合解析功能
    const transformClasses = parseTransformCombination(value);

    if (transformClasses.length > 0) {
      return transformClasses.join(' ');
    }

    // 降级处理
    return `[transform:${value}]`;
  },
  transition: (value: string) => {
    // 解析 transition 属性
    if (value === 'none') return 'transition-none';

    // 处理简单的 all 过渡
    if (value.startsWith('all ')) {
      const parts = value.split(' ');
      let classes = ['transition-all'];

      // 处理持续时间
      if (parts[1]) {
        const duration = convertDurationToTailwind(parts[1]);
        if (duration) classes.push(duration);
      }

      // 处理时序函数
      if (parts[2]) {
        const easing = convertEasingToTailwind(parts[2]);
        if (easing) classes.push(easing);
      }

      return classes.join(' ');
    }

    // 处理特定属性的过渡
    if (value.includes('transform') || value.includes('opacity') || value.includes('color')) {
      const parts = value.split(' ');
      let classes = ['transition'];

      // 处理持续时间
      if (parts[1]) {
        const duration = convertDurationToTailwind(parts[1]);
        if (duration) classes.push(duration);
      }

      // 处理时序函数
      if (parts[2]) {
        const easing = convertEasingToTailwind(parts[2]);
        if (easing) classes.push(easing);
      }

      return classes.join(' ');
    }

    return `[transition:${value}]`;
  },
  animation: (value: string) => {
    const animationMap: Record<string, string> = {
      none: 'animate-none',
      'spin 1s linear infinite': 'animate-spin',
      'ping 1s cubic-bezier(0, 0, 0.2, 1) infinite': 'animate-ping',
      'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite': 'animate-pulse',
      'bounce 1s infinite': 'animate-bounce',
    };

    return animationMap[value] || `[animation:${value}]`;
  },
  // 更新预设样式
  'rounded-button': 'borderRadius: 6px',
};

// Tailwind 类名到内联样式的映射
const enhancedTailwindToStyle: Record<string, string> = {
  // 文本颜色
  'text-gray-600': 'color: #718096',
  'text-gray-700': 'color: #4a5568',

  // 定位
  relative: 'position: relative',
  absolute: 'position: absolute',
  fixed: 'position: fixed',
  sticky: 'position: sticky',
  static: 'position: static',

  // Margin 6 和 8
  'mb-6': 'marginBottom: 24px',
  'mb-8': 'marginBottom: 32px',
  'mt-6': 'marginTop: 24px',
  'mt-8': 'marginTop: 32px',

  // 自定义背景渐变
  'bg-gradient-to-b': 'background: linear-gradient(to bottom)',
  'from-[#00a2ff]': 'background: linear-gradient(to bottom, #00a2ff)',
  'to-[#0077cc]': 'background: linear-gradient(to bottom, #00a2ff, #0077cc)',

  // 自定义间距
  'mt-[2px]': 'marginTop: 2px',

  // 自定义圆角
  'rounded-button': 'borderRadius: 6px',

  // Grid 流方向
  'grid-flow-row': 'gridFlow: row',
  'grid-flow-col': 'gridFlow: column',
  'grid-flow-dense': 'gridFlow: dense',
  'grid-flow-row-dense': 'gridFlow: row dense',
  'grid-flow-col-dense': 'gridFlow: column dense',

  // Grid 列跨度
  'col-span-2': 'gridColumn: span 2 / span 2',
  'col-span-3': 'gridColumn: span 3 / span 3',
  'col-span-4': 'gridColumn: span 4 / span 4',

  // 其他自定义属性
  'cursor-pointer': 'cursor: pointer',
  'tracking-wider': 'letterSpacing: 0.05em',
};

// 预设样式配置
const presetStyles: Record<string, string[]> = {
  'flex-center': ['flex', 'justify-center', 'items-center'],
  'text-primary': ['text-base', 'text-gray-900', 'font-medium'],
  // 添加更多预设...
};

export const EnhancedStyleTransformer: IEnhancedStyleTransformer = {
  toStyle: (style: Record<string, any>) => {
    const classes: string[] = [];
    const errors: string[] = [];

    Object.entries(style).forEach(([key, value]) => {
      try {
        const converter = enhancedStyleToTailwind[key];
        if (converter) {
          // 传递整个 style 对象，便于 background 逆向推断
          const result = converter(value as string, style);
          if (result && result.trim()) {
            classes.push(result);
          }
        } else {
          // 未支持的属性，使用自定义格式
          if (value && typeof value === 'string') {
            classes.push(`[${key}:${value}]`);
          }
        }
      } catch (error) {
        errors.push(`Failed to convert ${key}: ${value} - ${error}`);
        // 降级处理：使用自定义格式
        if (value && typeof value === 'string') {
          classes.push(`[${key}:${value}]`);
        }
      }
    });

    // 在开发环境下输出错误信息
    if (errors.length > 0 && process.env.NODE_ENV === 'development') {
      console.warn('Style conversion errors:', errors);
    }

    return classes.filter(Boolean).join(' ');
  },

  mergeClassesToStyle: (styles: string[]) => {
    const mergedStyle = styles.reduce((acc, style) => {
      try {
        const styleObj = JSON.parse(style);
        return { ...acc, ...styleObj };
      } catch (e) {
        console.warn('Style 解析失败:', e);
        return acc;
      }
    }, {});
    return EnhancedStyleTransformer.toStyle(mergedStyle);
  },

  extractSpecialClasses: (style: Record<string, any>) => {
    const result = {
      base: [] as string[],
      hover: [] as string[],
      responsive: {
        sm: [] as string[],
        md: [] as string[],
        lg: [] as string[],
        xl: [] as string[],
      },
    };

    Object.entries(style).forEach(([key, value]) => {
      const converter = enhancedStyleToTailwind[key];
      if (converter) {
        if (key.startsWith('hover')) {
          result.hover.push(converter(value as string));
        } else if (key.startsWith('sm:')) {
          result.responsive.sm.push(converter(value as string));
        } else if (key.startsWith('md:')) {
          result.responsive.md.push(converter(value as string));
        } else if (key.startsWith('lg:')) {
          result.responsive.lg.push(converter(value as string));
        } else if (key.startsWith('xl:')) {
          result.responsive.xl.push(converter(value as string));
        } else {
          result.base.push(converter(value as string));
        }
      }
    });

    return result;
  },

  toInlineStyle: (classNames: string[]) => {
    const style: Record<string, string> = {};
    const convertedClasses: string[] = [];
    const unconvertedClasses: string[] = [];
    const errors: string[] = [];

    // 输入验证
    if (!Array.isArray(classNames)) {
      errors.push('Input must be an array of class names');
      return {
        style: undefined,
        convertedClasses: [],
        unconvertedClasses: [],
        errors,
      };
    }

    // 智能冲突检测：检测伪类样式并识别冲突的基础样式
    const conflictDetection = analyzeStyleConflicts(classNames);
    const protectedClasses = conflictDetection.protectedClasses;

    // 检查类名是否需要跳过转换
    const shouldSkipConversion = (className: string): boolean => {
      // 检查是否是受保护的类名（与伪类冲突）
      if (protectedClasses.has(className)) {
        return true;
      }

      // 跳过所有 gap 相关类名，避免转换为内联样式
      if (/^gap-/.test(className)) return true;

      if (className.startsWith('animate-')) return true;
      if (className.startsWith('transition')) return true;
      if (
        className === 'transform' ||
        className === 'transform-gpu' ||
        className === 'transform-none'
      )
        return true;
      if (
        className.startsWith('hover:') ||
        className.startsWith('focus:') ||
        className.startsWith('active:') ||
        className.startsWith('disabled:')
      )
        return true;
      if (/^(sm|md|lg|xl|2xl):/.test(className)) return true;
      if (className.startsWith('dark:')) return true;
      if (className.startsWith('print:')) return true;
      return false;
    };

    // 处理z-index类
    const parseZIndex = (className: string) => {
      const zIndexMatch = className.match(/^z-(\d+|auto|\[.+\])$/);
      if (zIndexMatch) {
        const [, value] = zIndexMatch;
        if (value === 'auto') {
          style['zIndex'] = 'auto';
        } else if (value.startsWith('[') && value.endsWith(']')) {
          style['zIndex'] = value.slice(1, -1);
        } else {
          // 处理标准数字值
          style['zIndex'] = value;
        }
        return true;
      }
      return false;
    };

    const parseGenericPadding = (className: string) => {
      // 处理通用的 padding 相关类名，支持负值、特殊值中和括号自定义值
      const paddingMatch = className.match(/^p([xytrbl])?-(-?[\d.]+|auto|\[.+?\])$/);
      if (paddingMatch) {
        const [, direction, value] = paddingMatch;
        let paddingValue: string;
        if (value === 'auto') {
          paddingValue = 'auto';
        } else if (value.startsWith('[') && value.endsWith(']')) {
          paddingValue = value.slice(1, -1); // 移除中括号
        } else {
          paddingValue = `${parseInt(value) * 4}px`;
        }

        switch (direction) {
          case 'x':
            style['paddingLeft'] = paddingValue;
            style['paddingRight'] = paddingValue;
            break;
          case 'y':
            style['paddingTop'] = paddingValue;
            style['paddingBottom'] = paddingValue;
            break;
          case 't':
            style['paddingTop'] = paddingValue;
            break;
          case 'r':
            style['paddingRight'] = paddingValue;
            break;
          case 'b':
            style['paddingBottom'] = paddingValue;
            break;
          case 'l':
            style['paddingLeft'] = paddingValue;
            break;
          default:
            style['padding'] = paddingValue;
        }
        return true;
      }
      return false;
    };

    const parseGenericMargin = (className: string) => {
      // 处理通用的 margin 相关类名，支持负值、特殊值中和括号自定义值
      const marginMatch = className.match(/^m([xytrbl])?-(-?[\d.]+|auto|0|\[.+?\])$/);
      if (marginMatch) {
        const [, direction, value] = marginMatch;
        let marginValue: string;
        if (value === 'auto') {
          marginValue = 'auto';
        } else if (value === '0') {
          marginValue = '0';
        } else if (value.startsWith('[') && value.endsWith(']')) {
          marginValue = value.slice(1, -1); // 移除中括号
        } else {
          marginValue = `${parseInt(value) * 4}px`;
        }

        switch (direction) {
          case 'x':
            style['marginLeft'] = marginValue;
            style['marginRight'] = marginValue;
            break;
          case 'y':
            style['marginTop'] = marginValue;
            style['marginBottom'] = marginValue;
            break;
          case 't':
            style['marginTop'] = marginValue;
            break;
          case 'r':
            style['marginRight'] = marginValue;
            break;
          case 'b':
            style['marginBottom'] = marginValue;
            break;
          case 'l':
            style['marginLeft'] = marginValue;
            break;
          default:
            style['margin'] = marginValue;
        }
        return true;
      }
      return false;
    };

    // 通用尺寸解析函数
    const parseSizeValue = (value: string) => {
      if (value === 'auto') return 'auto';
      if (value === '0') return '0';
      if (value.startsWith('-')) return `-${parseInt(value.slice(1)) * 4}px`;
      return `${parseInt(value) * 4}px`;
    };

    // 处理宽度和高度
    const parseGenericSize = (className: string) => {
      const sizeMatch = className.match(
        /^(w|h)-(-?[\d.]+|auto|full|screen|\[.*?\]|[1-9]\d?\/?[1-9]?\d?)$/,
      );
      if (sizeMatch) {
        const [, type, value] = sizeMatch;
        const prop = type === 'w' ? 'width' : 'height';

        if (value === 'full') {
          style[prop] = '100%';
        } else if (value === 'screen') {
          style[prop] = type === 'w' ? '100vw' : '100vh';
        } else if (value.includes('/')) {
          // 处理分数值，如 w-1/2, w-2/3 等
          const [numerator, denominator] = value.split('/');
          style[prop] = `${(parseInt(numerator) / parseInt(denominator)) * 100}%`;
        } else if (value.startsWith('[') && value.endsWith(']')) {
          style[prop] = value.slice(1, -1);
        } else {
          style[prop] = parseSizeValue(value);
        }

        return true;
      }

      return false;
    };

    // 处理字体相关的类名
    const parseGenericFont = (className: string) => {
      // 处理字体大小 - 增强版本，支持更多格式
      const fontSizeMatch = className.match(
        /^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl|\[.*?\])$/,
      );
      if (fontSizeMatch) {
        const sizeMap: Record<string, string> = {
          xs: '12px',
          sm: '14px',
          base: '16px',
          lg: '18px',
          xl: '20px',
          '2xl': '24px',
          '3xl': '30px',
          '4xl': '36px',
          '5xl': '48px',
          '6xl': '60px',
          '7xl': '72px',
          '8xl': '96px',
          '9xl': '128px',
        };
        const [, size] = fontSizeMatch;
        if (size.startsWith('[') && size.endsWith(']')) {
          const value = size.slice(1, -1);
          // 判断是否为颜色值
          if (value.startsWith('#') || value.startsWith('rgb') || value.startsWith('hsl')) {
            style['color'] = value;
          } else if (
            value.includes('px') ||
            value.includes('rem') ||
            value.includes('em') ||
            /^\d+(\.\d+)?$/.test(value)
          ) {
            // 如果包含单位或者是纯数字，则认为是字体大小
            style['fontSize'] =
              value.includes('px') || value.includes('rem') || value.includes('em')
                ? value
                : `${value}px`;
          }
        } else {
          style['fontSize'] = sizeMap[size] || '16px';
        }
        return true;
      }

      // 处理字体粗细
      const fontWeightMatch = className.match(
        /^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black|\d+)$/,
      );
      if (fontWeightMatch) {
        const weightMap: Record<string, string> = {
          thin: '100',
          extralight: '200',
          light: '300',
          normal: '400',
          medium: '500',
          semibold: '600',
          bold: '700',
          extrabold: '800',
          black: '900',
        };
        const [, weight] = fontWeightMatch;
        // 如果是数字直接使用，否则查找映射表
        if (/^\d+$/.test(weight)) {
          style['fontWeight'] = weight;
        } else {
          style['fontWeight'] = weightMap[weight];
        }
        return true;
      }

      // 处理字体族
      if (className.startsWith('font-[') && className.endsWith(']')) {
        const fontFamily = className.slice(6, -1);
        style['fontFamily'] = fontFamily;
        return true;
      }

      return false;
    };

    // 处理圆角相关的类名
    const parseGenericBorderRadius = (className: string) => {
      // 处理特殊值
      if (className === 'rounded-none') {
        style['borderRadius'] = '0px';
        return true;
      }
      if (className === 'rounded-full') {
        style['borderRadius'] = '9999px';
        return true;
      }

      // 处理预设值
      const presetMap: Record<string, string> = {
        rounded: '4px',
        'rounded-sm': '2px',
        'rounded-md': '6px',
        'rounded-lg': '8px',
        'rounded-xl': '12px',
        'rounded-2xl': '16px',
        'rounded-3xl': '24px',
      };
      if (presetMap[className]) {
        style['borderRadius'] = presetMap[className];
        return true;
      }

      // 处理方向性圆角预设值
      const directionalPresetMatch = className.match(
        /^rounded-(t|r|b|l|tr|tl|br|bl)-(none|sm|md|lg|xl|2xl|3xl|full)$/,
      );
      if (directionalPresetMatch) {
        const [, position, size] = directionalPresetMatch;
        const valueMap: Record<string, string> = {
          none: '0px',
          sm: '2px',
          md: '6px',
          lg: '8px',
          xl: '12px',
          '2xl': '16px',
          '3xl': '24px',
          full: '9999px',
        };
        const radiusValue = valueMap[size];

        if (position.length === 1) {
          // 单边圆角
          const directionMap: Record<string, string> = {
            t: 'Top',
            r: 'Right',
            b: 'Bottom',
            l: 'Left',
          };
          style[`border${directionMap[position]}Radius`] = radiusValue;
        } else {
          // 角落圆角
          const cornerMap: Record<string, string> = {
            tr: 'TopRight',
            tl: 'TopLeft',
            br: 'BottomRight',
            bl: 'BottomLeft',
          };
          style[`border${cornerMap[position]}Radius`] = radiusValue;
        }
        return true;
      }

      // 处理数值和自定义值
      const roundedMatch = className.match(/^rounded(-[trbl][lr])?-([\d.]+|\[.*?\])$/);
      if (roundedMatch) {
        const [, position, value] = roundedMatch;
        let radiusValue: string;

        if (value.startsWith('[') && value.endsWith(']')) {
          radiusValue = value.slice(1, -1);
        } else {
          radiusValue = `${parseInt(value) * 4}px`;
        }

        if (!position) {
          style['borderRadius'] = radiusValue;
        } else {
          const [, first, second] = position.split('');
          const corner = `border${first.toUpperCase()}${second.toUpperCase()}Radius`;
          style[corner] = radiusValue;
        }
        return true;
      }

      return false;
    };

    // 辅助函数：将颜色名称转换为颜色值
    const colorNameToValue = (colorName: string) => {
      // 基础颜色映射
      const basicColors: Record<string, string> = {
        white: '#ffffff',
        black: '#000000',
        'gray-100': '#f3f4f6',
        'gray-200': '#e5e7eb',
        'gray-300': '#d1d5db',
        'gray-400': '#9ca3af',
        'gray-500': '#6b7280',
        'gray-600': '#4b5563',
        'gray-700': '#374151',
        'gray-800': '#1f2937',
        'gray-900': '#111827',
        'red-500': '#ef4444',
        'blue-500': '#3b82f6',
        'green-500': '#10b981',
        'yellow-500': '#f59e0b',
        'purple-500': '#8b5cf6',
        'pink-500': '#ec4899',
        'indigo-500': '#6366f1',
        primary: '#1890ff',
      };

      return basicColors[colorName] || `var(--${colorName})`;
    };

    // 解析颜色相关类名
    const parseGenericColor = (className: string) => {
      logger('尝试解析颜色:', className);

      // 跳过已知的特殊背景属性格式
      if (
        className.startsWith('bg-[position:') ||
        className.startsWith('bg-[length:') ||
        className.startsWith('bg-[repeat:') ||
        className.startsWith('bg-[url(')
      ) {
        logger('跳过特殊背景属性:', className);
        return false;
      }

      // 解析文本颜色
      const textColorMatch = className.match(/^text-(\[.+\]|[a-zA-Z0-9_-]+)$/);
      if (textColorMatch) {
        const [, colorValue] = textColorMatch;
        if (colorValue.startsWith('[') && colorValue.endsWith(']')) {
          // 处理自定义颜色值
          const customColor = colorValue.slice(1, -1);
          style.color = customColor.startsWith('var(--') ? customColor : customColor;
        } else {
          // 处理预设颜色
          style.color = colorNameToValue(colorValue);
        }
        return true;
      }

      // 解析背景颜色 - 确保不会错误解析其他背景属性
      const bgColorMatch = className.match(/^bg-(\[.+\]|[a-zA-Z0-9_-]+)$/);
      if (bgColorMatch) {
        const [, colorValue] = bgColorMatch;

        // 检查是否是特殊背景属性
        if (colorValue.startsWith('[') && colorValue.endsWith(']')) {
          const innerValue = colorValue.slice(1, -1);

          // 如果包含特殊前缀，则不是颜色
          if (
            innerValue.startsWith('position:') ||
            innerValue.startsWith('length:') ||
            innerValue.startsWith('repeat:') ||
            innerValue.startsWith('url(')
          ) {
            logger('在颜色解析中跳过特殊背景属性:', className);
            return false;
          }

          // 处理自定义颜色值
          style.backgroundColor = innerValue.startsWith('var(--') ? innerValue : innerValue;
        } else {
          // 处理预设颜色
          style.backgroundColor = colorNameToValue(colorValue);
        }
        return true;
      }

      // 解析边框颜色
      // ... existing code ...

      return false;
    };

    // 处理边框样式
    const parseGenericBorder = (className: string) => {
      logger('borderColorMatch ------: ', className);

      // 处理 border-[#颜色值] 格式
      const customBorderColorMatch = className.match(
        /^border-\[(#[0-9a-fA-F]{3,6}|rgb\(.*?\)|rgba\(.*?\))\]$/,
      );
      if (customBorderColorMatch) {
        const [, colorValue] = customBorderColorMatch;
        style['borderColor'] = colorValue;
        style['borderWidth'] = '1px';
        style['borderStyle'] = 'solid';
        return true;
      }

      // 处理基本边框
      if (className === 'border') {
        style['borderWidth'] = '1px';
        style['borderStyle'] = 'solid';
        return true;
      }

      // 处理边框方向
      const borderDirectionMatch = className.match(/^border-(t|r|b|l)$/);
      if (borderDirectionMatch) {
        const [, direction] = borderDirectionMatch;
        const directionMap: Record<string, string> = {
          t: 'Top',
          r: 'Right',
          b: 'Bottom',
          l: 'Left',
        };
        style[`border${directionMap[direction]}Width`] = '1px';
        style[`border${directionMap[direction]}Style`] = 'solid';
        return true;
      }

      // 处理边框宽度
      const borderWidthMatch = className.match(/^border-(t|r|b|l)?-(\d+|\[.*?\])$/);
      if (borderWidthMatch) {
        const [, direction, width] = borderWidthMatch;
        let widthValue = width.includes('[') ? width.slice(1, -1) : `${parseInt(width) * 4}px`;

        if (direction || borderWidthMatch[1]) {
          const directionMap: Record<string, string> = {
            t: 'Top',
            r: 'Right',
            b: 'Bottom',
            l: 'Left',
          };
          if (widthValue.includes('#') || widthValue.startsWith('rgb')) {
            style[`border${directionMap[direction]}Color`] = widthValue;
          } else {
            style[`border${directionMap[direction]}Width`] = widthValue;
            style[`border${directionMap[direction]}Style`] = 'solid';
          }
        } else {
          if (widthValue.includes('#') || widthValue.startsWith('rgb')) {
            style['borderColor'] = widthValue;
          } else {
            style['borderWidth'] = widthValue;
            style['borderStyle'] = 'solid';
          }
        }
        return true;
      }

      logger('borderColorMatch 222222 ', className);
      // 处理边框样式
      const borderStyleMatch = className.match(
        /^border-(t|r|b|l)?-(solid|dashed|dotted|double|none)$/,
      );
      if (borderStyleMatch) {
        const [, direction, borderStyle] = borderStyleMatch;

        if (direction) {
          const directionMap: Record<string, string> = {
            t: 'Top',
            r: 'Right',
            b: 'Bottom',
            l: 'Left',
          };
          style[`border${directionMap[direction]}Style`] = borderStyle;
        } else {
          style['borderStyle'] = borderStyle;
        }
        return true;
      }

      // 处理边框颜色
      const borderColorMatch = className.match(/^border-(t|r|b|l)?-(\[.+?\]|[a-z]+-?[a-z0-9]*)$/);
      logger('borderColorMatch: ', className, borderColorMatch);
      if (borderColorMatch) {
        const [, direction, color] = borderColorMatch;
        let colorValue: string;

        if (color.startsWith('[') && color.endsWith(']')) {
          colorValue = color.slice(1, -1);
        } else {
          // 处理预设颜色
          colorValue = `var(--${color})`;
          // 特殊处理黑白色
          if (color === 'white') colorValue = '#ffffff';
          if (color === 'black') colorValue = '#000000';
        }

        if (direction) {
          const directionMap: Record<string, string> = {
            t: 'Top',
            r: 'Right',
            b: 'Bottom',
            l: 'Left',
          };
          style[`border${directionMap[direction]}Color`] = colorValue;
        } else {
          style['borderColor'] = colorValue;
        }
        return true;
      }

      return false;
    };

    // 处理 overflow 相关类名
    const parseGenericOverflow = (className: string) => {
      // 处理基本overflow
      if (
        className === 'overflow-auto' ||
        className === 'overflow-hidden' ||
        className === 'overflow-visible' ||
        className === 'overflow-scroll' ||
        className === 'overflow-clip'
      ) {
        style['overflow'] = className.replace('overflow-', '');
        return true;
      }

      // 处理overflow-x和overflow-y
      const overflowMatch = className.match(/^overflow-(x|y)-(auto|hidden|visible|scroll|clip)$/);
      if (overflowMatch) {
        const [, direction, value] = overflowMatch;
        style[`overflow${direction.toUpperCase()}`] = value;
        return true;
      }
      return false;
    };

    // 处理 flex 相关的类名
    const parseGenericFlex = (className: string) => {
      // 处理 display: flex
      if (className === 'flex') {
        style['display'] = 'flex';
        return true;
      }

      // 处理 flex-row 和 flex-col
      if (className === 'flex-row') {
        style['flexDirection'] = 'row';
        return true;
      }

      if (className === 'flex-col') {
        style['flexDirection'] = 'column';
        return true;
      }

      // 处理 flex-wrap 和 flex-nowrap
      if (className === 'flex-wrap') {
        style['flexWrap'] = 'wrap';
        return true;
      }

      if (className === 'flex-nowrap') {
        style['flexWrap'] = 'nowrap';
        return true;
      }

      // 处理 justify-content
      const justifyMatch = className.match(/^justify-(start|end|center|between|around|evenly)$/);
      if (justifyMatch) {
        const [, value] = justifyMatch;
        const justifyMap: Record<string, string> = {
          start: 'flex-start',
          end: 'flex-end',
          center: 'center',
          between: 'space-between',
          around: 'space-around',
          evenly: 'space-evenly',
        };
        style['justifyContent'] = justifyMap[value];
        return true;
      }

      // 处理 items-align
      const itemsMatch = className.match(/^items-(start|end|center|baseline|stretch)$/);
      if (itemsMatch) {
        const [, value] = itemsMatch;
        const itemsMap: Record<string, string> = {
          start: 'flex-start',
          end: 'flex-end',
          center: 'center',
          baseline: 'baseline',
          stretch: 'stretch',
        };
        style['alignItems'] = itemsMap[value];
        return true;
      }

      // 处理 flex 值
      if (className.startsWith('flex-')) {
        const value = className.replace('flex-', '');
        if (
          ['auto', 'initial', 'none'].includes(value) ||
          (!isNaN(Number(value)) && Number(value) >= 1 && Number(value) <= 12)
        ) {
          const valueMap: Record<string, string> = {
            '1': '1',
            '2': '2',
            '3': '3',
            '4': '4',
            '5': '5',
            '6': '6',
            '7': '7',
            '8': '8',
            '9': '9',
            '10': '10',
            '11': '11',
            '12': '12',
            auto: '1 1 auto',
            initial: '0 1 auto',
            none: 'none',
          };
          style['flex'] = valueMap[value];
          return true;
        }

        // 处理 flex-grow/shrink
        const flexGrowShrinkMatch = className.match(/^flex-(grow|shrink)(-[0-9])?$/);
        if (flexGrowShrinkMatch) {
          const [, prop, value = ''] = flexGrowShrinkMatch;
          // 如果没有指定值，默认为1
          const numValue = value ? value.substring(1) : '1';
          style[`flex${prop.charAt(0).toUpperCase() + prop.slice(1)}`] = numValue;
          return true;
        }

        // 处理 flex-basis
        const flexBasisMatch = className.match(/^flex-basis-(.+)$/);
        if (flexBasisMatch) {
          const [, value] = flexBasisMatch;
          if (value.includes('/')) {
            // 处理分数值，如 flex-basis-1/2
            const [numerator, denominator] = value.split('/');
            style['flexBasis'] = `${(parseInt(numerator) / parseInt(denominator)) * 100}%`;
          } else if (value === 'auto') {
            style['flexBasis'] = 'auto';
          } else if (value === 'full') {
            style['flexBasis'] = '100%';
          } else {
            style['flexBasis'] = `${parseInt(value) * 4}px`;
          }
          return true;
        }

        return false;
      }
      return false;
    };
    // 处理 min/max 宽高
    const parseGenericMinMaxSize = (className: string) => {
      const minMaxMatch = className.match(
        /^(min|max)-(w|h)-([a-z0-9]+|\[.*?\]|full|screen|fit|max|min)$/,
      );
      if (minMaxMatch) {
        const [, minMax, dimension, value] = minMaxMatch;
        const prop = `${minMax}${dimension === 'w' ? 'Width' : 'Height'}`;

        if (value.startsWith('[') && value.endsWith(']')) {
          style[prop] = value.slice(1, -1);
        } else if (value === 'full') {
          style[prop] = '100%';
        } else if (value === 'screen') {
          style[prop] = dimension === 'w' ? '100vw' : '100vh';
        } else if (value === 'fit') {
          style[prop] = 'fit-content';
        } else if (value === 'max') {
          style[prop] = 'max-content';
        } else if (value === 'min') {
          style[prop] = 'min-content';
        } else if (value.includes('/')) {
          // 处理分数值，如 min-w-1/2
          const [numerator, denominator] = value.split('/');
          style[prop] = `${(parseInt(numerator) / parseInt(denominator)) * 100}%`;
        } else if (/^\d+$/.test(value)) {
          style[prop] = `${parseInt(value) * 4}px`;
        }
        return true;
      }
      return false;
    };

    const parseGenericBoxShadow = (className: string) => {
      // 处理预设阴影
      const shadowMatch = className.match(/^shadow(-[a-z0-9]+)?$/i);
      if (shadowMatch) {
        const [, size = ''] = shadowMatch;
        const shadowMap: Record<string, string> = {
          '': '0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)',
          '-sm': '0 1px 2px 0 rgb(0 0 0 / 0.05)',
          '-md': '0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)',
          '-lg': '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)',
          '-xl': '0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)',
          '-2xl': '0 25px 50px -12px rgb(0 0 0 / 0.25)',
          '-inner': 'inset 0 2px 4px 0 rgb(0 0 0 / 0.05)',
          '-none': 'none',
        };
        style['boxShadow'] = shadowMap[size];
        return true;
      }

      // 处理自定义阴影值
      const customShadowMatch = className.match(/^shadow-\[(.*?)\]$/);
      if (customShadowMatch) {
        const [, value] = customShadowMatch;
        style['boxShadow'] = value;
        return true;
      }

      // 处理阴影颜色
      const shadowColorMatch = className.match(/^shadow-(color|opacity)-(.+)$/);
      if (shadowColorMatch) {
        const [, type, value] = shadowColorMatch;
        if (type === 'color') {
          if (value.startsWith('[') && value.endsWith(']')) {
            // 自定义颜色值
            style['--tw-shadow-color'] = value.slice(1, -1);
            style['boxShadowColor'] = value.slice(1, -1);
          } else {
            // 预设颜色
            const colorValue =
              value === 'white' ? '#ffffff' : value === 'black' ? '#000000' : `var(--${value})`;
            style['--tw-shadow-color'] = colorValue;
            style['boxShadowColor'] = colorValue;
          }
        } else if (type === 'opacity') {
          // 处理阴影透明度
          const opacity = parseInt(value) / 100;
          style['--tw-shadow-opacity'] = opacity.toString();
        }
        return true;
      }

      return false;
    };

    // 处理 Grid 相关类名
    const parseGridStyles = (className: string) => {
      // 处理 Grid 容器
      if (className === 'grid') {
        style['display'] = 'grid';
        return true;
      }

      // 处理 Grid 流
      const gridFlowMatch = className.match(/^grid-flow-(row|col)(-dense)?$/);
      if (gridFlowMatch) {
        const [, direction, dense] = gridFlowMatch;
        style['gridFlow'] = dense ? `${direction} dense` : direction;
        return true;
      }

      // 处理 Grid 列 - 标准格式
      const gridColsMatch = className.match(/^grid-cols-(\d+|none)$/);
      if (gridColsMatch) {
        const [, value] = gridColsMatch;
        style['gridTemplateColumns'] =
          value === 'none' ? 'none' : `repeat(${value}, minmax(0, 1fr))`;
        return true;
      }

      // 处理 Grid 列 - 自定义格式 grid-cols-[200px_minmax(900px,_1fr)_100px]
      const gridColsCustomMatch = className.match(/^grid-cols-\[(.+)\]$/);
      if (gridColsCustomMatch) {
        const [, value] = gridColsCustomMatch;
        // 将下划线替换回空格，恢复原始的 CSS 格式
        const normalizedValue = value.replace(/_/g, ' ');
        style['gridTemplateColumns'] = normalizedValue;
        return true;
      }

      // 处理 Grid 行 - 标准格式
      const gridRowsMatch = className.match(/^grid-rows-(\d+|none)$/);
      if (gridRowsMatch) {
        const [, value] = gridRowsMatch;
        style['gridTemplateRows'] = value === 'none' ? 'none' : `repeat(${value}, minmax(0, 1fr))`;
        return true;
      }

      // 处理 Grid 行 - 自定义格式 grid-rows-[200px_minmax(900px,_1fr)_100px]
      const gridRowsCustomMatch = className.match(/^grid-rows-\[(.+)\]$/);
      if (gridRowsCustomMatch) {
        const [, value] = gridRowsCustomMatch;
        // 将下划线替换回空格，恢复原始的 CSS 格式
        const normalizedValue = value.replace(/_/g, ' ');
        style['gridTemplateRows'] = normalizedValue;
        return true;
      }

      // 处理 Grid 项目跨度
      const spanMatch = className.match(/^(col|row)-span-(\d+|full)$/);
      if (spanMatch) {
        const [, type, value] = spanMatch;
        const property = type === 'col' ? 'gridColumn' : 'gridRow';
        style[property] = value === 'full' ? '1 / -1' : `span ${value} / span ${value}`;
        return true;
      }

      // 处理 Grid 项目位置
      const positionMatch = className.match(/^(col|row)-(start|end)-(\d+|auto)$/);
      if (positionMatch) {
        const [, type, position, value] = positionMatch;
        const property = `grid${type === 'col' ? 'Column' : 'Row'}${
          position === 'start' ? 'Start' : 'End'
        }`;
        style[property] = value;
        return true;
      }

      // 处理自动列/行
      const autoMatch = className.match(/^auto-(cols|rows)-(auto|min|max|fr)$/);
      if (autoMatch) {
        const [, type, value] = autoMatch;
        const property = `gridAuto${type === 'cols' ? 'Columns' : 'Rows'}`;
        const valueMap: Record<string, string> = {
          auto: 'auto',
          min: 'min-content',
          max: 'max-content',
          fr: 'minmax(0, 1fr)',
        };
        style[property] = valueMap[value];
        return true;
      }

      return false;
    };

    // 处理动画相关类名
    const parseAnimationStyles = (className: string) => {
      // 处理过渡
      if (className.startsWith('transition')) {
        const value = className.replace('transition-', '');
        const transitionMap: Record<string, string> = {
          '': 'all 0.2s ease',
          none: 'none',
          all: 'all 0.2s ease',
          colors: 'background-color 0.2s ease, border-color 0.2s ease, color 0.2s ease',
          opacity: 'opacity 0.2s ease',
          shadow: 'box-shadow 0.2s ease',
          transform: 'transform 0.2s ease',
        };
        style['transition'] = transitionMap[value] || value;
        return true;
      }

      // 处理动画
      if (className.startsWith('animate-')) {
        const value = className.replace('animate-', '');
        const animationMap: Record<string, string> = {
          none: 'none',
          spin: 'spin 1s linear infinite',
          ping: 'ping 1s cubic-bezier(0, 0, 0.2, 1) infinite',
          pulse: 'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite',
          bounce: 'bounce 1s infinite',
        };
        style['animation'] = animationMap[value] || value;
        return true;
      }

      // 处理变换
      if (className === 'transform') {
        style['transform'] = 'translateZ(0)';
        return true;
      }

      // 处理缩放
      const scaleMatch = className.match(/^scale-(\d+|\[.*?\])$/);
      if (scaleMatch) {
        const [, value] = scaleMatch;
        if (value.startsWith('[') && value.endsWith(']')) {
          style['transform'] = `scale(${value.slice(1, -1)})`;
        } else {
          const scaleMap: Record<string, string> = {
            '0': '0',
            '50': '0.5',
            '75': '0.75',
            '90': '0.9',
            '95': '0.95',
            '100': '1',
            '105': '1.05',
            '110': '1.1',
            '125': '1.25',
            '150': '1.5',
          };
          style['transform'] = `scale(${scaleMap[value] || value})`;
        }
        return true;
      }

      // 处理旋转
      const rotateMatch = className.match(/^rotate-(\d+|\[.*?\])$/);
      if (rotateMatch) {
        const [, value] = rotateMatch;
        if (value.startsWith('[') && value.endsWith(']')) {
          style['transform'] = `rotate(${value.slice(1, -1)})`;
        } else {
          style['transform'] = `rotate(${value}deg)`;
        }
        return true;
      }

      // 处理平移
      const translateMatch = className.match(
        /^translate-([xy])-(\d+|\[.*?\]|px|0\.5|1\.5|2\.5|3\.5)$/,
      );
      if (translateMatch) {
        const [, axis, value] = translateMatch;
        let translateValue: string;
        if (value.startsWith('[') && value.endsWith(']')) {
          translateValue = value.slice(1, -1);
        } else if (value === 'px') {
          translateValue = '1px';
        } else if (value.includes('.')) {
          translateValue = `${parseFloat(value) * 4}px`;
        } else {
          translateValue = `${parseInt(value) * 4}px`;
        }
        style['transform'] = `translate${axis.toUpperCase()}(${translateValue})`;
        return true;
      }

      return false;
    };

    // 处理交互状态相关类名
    const parseInteractionStyles = (className: string) => {
      // 处理悬停状态
      if (className.startsWith('hover:')) {
        const value = className.replace('hover:', '');
        const hoverStyle = enhancedTailwindToStyle[value];
        if (hoverStyle) {
          style['&:hover'] = hoverStyle;
          return true;
        }
      }

      // 处理焦点状态
      if (className.startsWith('focus:')) {
        const value = className.replace('focus:', '');
        const focusStyle = enhancedTailwindToStyle[value];
        if (focusStyle) {
          style['&:focus'] = focusStyle;
          return true;
        }
      }

      // 处理激活状态
      if (className.startsWith('active:')) {
        const value = className.replace('active:', '');
        const activeStyle = enhancedTailwindToStyle[value];
        if (activeStyle) {
          style['&:active'] = activeStyle;
          return true;
        }
      }

      // 处理禁用状态
      if (className.startsWith('disabled:')) {
        const value = className.replace('disabled:', '');
        const disabledStyle = enhancedTailwindToStyle[value];
        if (disabledStyle) {
          style['&:disabled'] = disabledStyle;
          return true;
        }
      }

      return false;
    };

    // 处理响应式设计相关类名
    const parseResponsiveStyles = (className: string) => {
      const breakpoints = ['sm', 'md', 'lg', 'xl', '2xl'];
      const breakpointMatch = className.match(new RegExp(`^(${breakpoints.join('|')}):(.+)$`));

      if (breakpointMatch) {
        const [, breakpoint, value] = breakpointMatch;
        const mediaQuery = {
          sm: 'min-width: 640px',
          md: 'min-width: 768px',
          lg: 'min-width: 1024px',
          xl: 'min-width: 1280px',
          '2xl': 'min-width: 1536px',
        }[breakpoint];

        const responsiveStyle = enhancedTailwindToStyle[value];
        if (responsiveStyle) {
          style[`@media (${mediaQuery})`] = responsiveStyle;
          return true;
        }
      }

      return false;
    };

    // 处理暗色模式相关类名
    const parseDarkModeStyles = (className: string) => {
      if (className.startsWith('dark:')) {
        const value = className.replace('dark:', '');
        const darkStyle = enhancedTailwindToStyle[value];
        if (darkStyle) {
          style['@media (prefers-color-scheme: dark)'] = darkStyle;
          return true;
        }
      }
      return false;
    };

    // 处理打印样式相关类名
    const parsePrintStyles = (className: string) => {
      if (className.startsWith('print:')) {
        const value = className.replace('print:', '');
        const printStyle = enhancedTailwindToStyle[value];
        if (printStyle) {
          style['@media print'] = printStyle;
          return true;
        }
      }
      return false;
    };

    const parseBackgroundStyles = (className: string) => {
      // 跳过已经被复杂渐变处理的类名
      if (complexGradientInfo.isValid && complexGradientInfo.classNames.includes(className)) {
        return false;
      }

      // 解析背景图片
      if (className.startsWith('bg-[url(')) {
        const bgValue = className.match(/bg-\[url\((.*?)\)\]/)?.[1];
        if (bgValue) {
          style.backgroundImage = `url(${bgValue})`;
          return true;
        }
      }

      // 处理复杂渐变格式（径向渐变、锥形渐变等）
      if (
        className.startsWith('bg-[') &&
        (className.includes('url(') || className.includes('gradient'))
      ) {
        const bgValue = className.match(/bg-\[(.*?)\]/)?.[1];
        if (bgValue) {
          // 处理包含 var(--tw-gradient-stops) 的复杂渐变
          if (bgValue.includes('var(--tw-gradient-stops)')) {
            // 这种情况需要结合后续的 from-/via-/to- 类名来构建完整的渐变
            // 注意：这里暂时设置为 backgroundImage，后续会被 parseComplexGradientWithColors 处理并替换为 background
            style.backgroundImage = bgValue;
            return true;
          } else {
            // 普通的自定义渐变 - 使用 background 属性以确保兼容性
            if (bgValue.includes('gradient')) {
              // 修复下划线格式：将下划线替换为空格以符合 CSS 语法
              const fixedGradient = bgValue.replace(/_/g, ' ');
              style.background = fixedGradient;
            } else {
              // 非渐变背景图片使用 backgroundImage
              style.backgroundImage = bgValue;
            }
            return true;
          }
        }
      }

      // 解析背景重复
      if (className.startsWith('bg-[repeat:')) {
        const repeatValue = className.match(/bg-\[repeat:(.*?)\]/)?.[1];
        if (repeatValue) {
          logger('匹配到背景重复:', repeatValue);
          style.backgroundRepeat = repeatValue;
          return true;
        }
      }

      // 解析预设背景重复
      if (
        [
          'bg-repeat',
          'bg-no-repeat',
          'bg-repeat-x',
          'bg-repeat-y',
          'bg-repeat-round',
          'bg-repeat-space',
        ].includes(className)
      ) {
        logger('匹配到预设背景重复:', className);
        style.backgroundRepeat = className.replace('bg-', '').replace('repeat-', 'repeat ');
        return true;
      }

      // 解析背景尺寸
      if (className.startsWith('bg-[length:')) {
        const sizeValue = className.match(/bg-\[length:(.*?)\]/)?.[1];
        if (sizeValue) {
          logger('匹配到背景尺寸:', sizeValue);
          style.backgroundSize = sizeValue;
          return true;
        }
      }

      // 解析背景位置
      if (className.startsWith('bg-[position:')) {
        logger('尝试匹配背景位置:', className);
        const posValue = className.match(/bg-\[position:(.*?)\]/)?.[1];
        logger('背景位置匹配结果:', posValue);
        if (posValue) {
          logger('设置背景位置为:', posValue);
          style.backgroundPosition = posValue;
          return true;
        }
      }

      // 解析预设背景尺寸
      if (['bg-auto', 'bg-cover', 'bg-contain'].includes(className)) {
        logger('匹配到预设背景尺寸:', className);
        style.backgroundSize = className.replace('bg-', '');
        return true;
      }

      // 解析预设背景位置
      const bgPositionMatch = className.match(
        /^bg-(center|top|bottom|left|right|left-top|right-top|left-bottom|right-bottom)$/,
      );
      if (bgPositionMatch) {
        const position = bgPositionMatch[1].replace('-', ' ');
        logger('匹配到预设背景位置:', position);
        style.backgroundPosition = position;
        return true;
      }

      logger('未匹配到背景样式:', className);
      return false;
    };

    const parseTextShadowStyles = (className: string) => {
      // 解析文本阴影
      if (className.startsWith('text-shadow-[')) {
        const shadowValue = className.match(/text-shadow-\[(.*?)\]/)?.[1];
        if (shadowValue) {
          style.textShadow = shadowValue;
          return true;
        }
      }

      // 解析预设文本阴影
      const textShadowMatch = className.match(/^text-shadow(-none|-sm|-md|-lg|-xl|-2xl)?$/);
      if (textShadowMatch) {
        const shadowSize = textShadowMatch[1] || '';
        const shadowMap: Record<string, string> = {
          '': '0 2px 4px rgba(0,0,0,0.1)',
          '-none': 'none',
          '-sm': '0 1px 3px rgba(0,0,0,0.1)',
          '-md': '0 4px 8px rgba(0,0,0,0.1)',
          '-lg': '0 8px 16px rgba(0,0,0,0.1)',
          '-xl': '0 12px 24px rgba(0,0,0,0.1)',
          '-2xl': '0 16px 32px rgba(0,0,0,0.1)',
        };
        style.textShadow = shadowMap[shadowSize];
        return true;
      }

      return false;
    };

    // 处理文本对齐方式
    const parseTextAlign = (className: string) => {
      const textAlignMatch = className.match(/^text-(left|center|right|justify)$/);
      if (textAlignMatch) {
        const [, align] = textAlignMatch;
        style['textAlign'] = align;
        return true;
      }
      return false;
    };

    // 处理文本装饰
    const parseTextDecoration = (className: string) => {
      if (className === 'underline') {
        style['textDecoration'] = 'underline';
        return true;
      }
      if (className === 'line-through') {
        style['textDecoration'] = 'line-through';
        return true;
      }
      if (className === 'no-underline') {
        style['textDecoration'] = 'none';
        return true;
      }
      return false;
    };

    // 处理透明度
    const parseOpacity = (className: string) => {
      const opacityMatch = className.match(/^opacity-(\d+)$/);
      if (opacityMatch) {
        const [, value] = opacityMatch;
        style['opacity'] = (parseInt(value) / 100).toString();
        return true;
      }
      return false;
    };

    const parsePositionStyles = (className: string) => {
      // 处理 right-[5px], top-[5px] 等格式
      const positionMatch = className.match(/^(top|right|bottom|left)-\[([^\]]+)\]$/);
      if (positionMatch) {
        const [, position, value] = positionMatch;
        style[position] = value;
        return true;
      }

      // 处理数字格式 top-1, bottom-5 等
      const numericPositionMatch = className.match(/^(top|right|bottom|left)-(\d+)$/);
      if (numericPositionMatch) {
        const [, position, value] = numericPositionMatch;
        style[position] = `${parseInt(value) * 4}px`;
        return true;
      }

      // 处理预设值
      const presetPositionMatch = className.match(/^(top|right|bottom|left)-(0|auto)$/);
      if (presetPositionMatch) {
        const [, position, value] = presetPositionMatch;
        style[position] = value;
        return true;
      }

      return false;
    };

    const parseGapStyles = (className: string) => {
      // 处理基础 gap (支持小数点，如 gap-0.5)
      const gapMatch = className.match(/^gap-([\d.]+|\[.*?\])$/);
      if (gapMatch) {
        const [, value] = gapMatch;
        if (value.startsWith('[') && value.endsWith(']')) {
          style['gap'] = value.slice(1, -1);
        } else {
          // 使用 px 单位，支持小数点
          style['gap'] = `${parseFloat(value) * 4}px`;
        }
        return true;
      }

      // 处理方向性 gap (支持小数点，如 gap-x-0.5)
      const directionalGapMatch = className.match(/^gap-([xy])-([\d.]+|\[.*?\])$/);
      if (directionalGapMatch) {
        const [, direction, value] = directionalGapMatch;
        const property = direction === 'x' ? 'columnGap' : 'rowGap';
        if (value.startsWith('[') && value.endsWith(']')) {
          style[property] = value.slice(1, -1);
        } else {
          // 使用 px 单位，支持小数点
          style[property] = `${parseFloat(value) * 4}px`;
        }
        return true;
      }

      return false;
    };

    const parseCursorStyles = (className: string) => {
      const cursorMatch = className.match(
        /^cursor-(auto|default|pointer|wait|text|move|not-allowed)$/,
      );
      if (cursorMatch) {
        const [, value] = cursorMatch;
        style['cursor'] = value;
        return true;
      }
      return false;
    };

    const parseLetterSpacingStyles = (className: string) => {
      const letterSpacingMatch = className.match(
        /^tracking-(tighter|tight|normal|wide|wider|widest)$/,
      );
      if (letterSpacingMatch) {
        const [, value] = letterSpacingMatch;
        const spacingMap: Record<string, string> = {
          tighter: '-0.05em',
          tight: '-0.025em',
          normal: '0em',
          wide: '0.025em',
          wider: '0.05em',
          widest: '0.1em',
        };
        style['letterSpacing'] = spacingMap[value];
        return true;
      }
      return false;
    };

    const parseLineHeightStyles = (className: string) => {
      const lineHeightMatch = className.match(
        /^leading-(\d+|none|tight|snug|normal|relaxed|loose)$/,
      );
      if (lineHeightMatch) {
        const [, value] = lineHeightMatch;
        const heightMap: Record<string, string> = {
          none: '1',
          tight: '1.25',
          snug: '1.375',
          normal: '1.5',
          relaxed: '1.625',
          loose: '2',
        };
        style['lineHeight'] = heightMap[value] || value;
        return true;
      }
      return false;
    };

    const parseTextTransformStyles = (className: string) => {
      const transformMap: Record<string, string> = {
        uppercase: 'uppercase',
        lowercase: 'lowercase',
        capitalize: 'capitalize',
        'normal-case': 'none',
      };
      if (transformMap[className]) {
        style['textTransform'] = transformMap[className];
        return true;
      }
      return false;
    };

    const parseWhiteSpaceStyles = (className: string) => {
      const whiteSpaceMap: Record<string, string> = {
        'whitespace-normal': 'normal',
        'whitespace-nowrap': 'nowrap',
        'whitespace-pre': 'pre',
        'whitespace-pre-line': 'pre-line',
        'whitespace-pre-wrap': 'pre-wrap',
      };
      if (whiteSpaceMap[className]) {
        style['whiteSpace'] = whiteSpaceMap[className];
        return true;
      }
      return false;
    };

    const parseWordBreakStyles = (className: string) => {
      const wordBreakMap: Record<string, string> = {
        'break-normal': 'normal',
        'break-words': 'break-word',
        'break-all': 'break-all',
        'break-keep': 'keep-all',
      };
      if (wordBreakMap[className]) {
        style['wordBreak'] = wordBreakMap[className];
        return true;
      }
      return false;
    };

    const parseTextOverflowStyles = (className: string) => {
      if (className === 'truncate') {
        style['overflow'] = 'hidden';
        style['textOverflow'] = 'ellipsis';
        style['whiteSpace'] = 'nowrap';
        return true;
      }
      return false;
    };

    const parseListStyleStyles = (className: string) => {
      const listStyleMap: Record<string, string> = {
        'list-none': 'none',
        'list-disc': 'disc',
        'list-decimal': 'decimal',
      };
      if (listStyleMap[className]) {
        style['listStyleType'] = listStyleMap[className];
        return true;
      }
      return false;
    };

    const parseObjectFitStyles = (className: string) => {
      const objectFitMap: Record<string, string> = {
        'object-contain': 'contain',
        'object-cover': 'cover',
        'object-fill': 'fill',
        'object-none': 'none',
        'object-scale-down': 'scale-down',
      };
      if (objectFitMap[className]) {
        style['objectFit'] = objectFitMap[className];
        return true;
      }
      return false;
    };

    const parseTransformOriginStyles = (className: string) => {
      const originMap: Record<string, string> = {
        'origin-center': 'center',
        'origin-top': 'top',
        'origin-top-right': 'top right',
        'origin-right': 'right',
        'origin-bottom-right': 'bottom right',
        'origin-bottom': 'bottom',
        'origin-bottom-left': 'bottom left',
        'origin-left': 'left',
        'origin-top-left': 'top left',
      };
      if (originMap[className]) {
        style['transformOrigin'] = originMap[className];
        return true;
      }
      return false;
    };

    // 渐变类收集与组装 - 增强版本支持复杂渐变
    const gradientInfo = parseGradientClasses(classNames);

    if (gradientInfo.isValid) {
      const { direction, colors, isTextGradient, classNames: gradientClassNames } = gradientInfo;

      // 构建 CSS linear-gradient
      const directionMap: Record<string, string> = {
        r: '90deg',
        l: '270deg',
        t: '0deg',
        b: '180deg',
        tr: '45deg',
        tl: '315deg',
        br: '135deg',
        bl: '225deg',
      };

      const angle = directionMap[direction] || direction;
      const colorString = colors
        .map((c) => (c.position ? `${c.color} ${c.position}` : c.color))
        .join(', ');

      style.background = `linear-gradient(${angle}, ${colorString})`;

      if (isTextGradient) {
        style.backgroundClip = 'text';
        style.WebkitBackgroundClip = 'text';
        style.color = 'transparent';
      }

      convertedClasses.push(...gradientClassNames);
    }

    // 处理复杂渐变（径向渐变、锥形渐变）与颜色组合
    const complexGradientInfo = parseComplexGradientWithColors(classNames);
    if (complexGradientInfo.isValid) {
      const {
        baseGradient,
        colors,
        isTextGradient,
        classNames: complexGradientClassNames,
      } = complexGradientInfo;

      // 替换 var(--tw-gradient-stops) 为实际颜色
      const colorString = colors
        .map((c) => (c.position ? `${c.color} ${c.position}` : c.color))
        .join(', ');
      let finalGradient = baseGradient!.replace('var(--tw-gradient-stops)', colorString);

      // 修复下划线格式：将下划线替换为空格以符合 CSS 语法
      finalGradient = finalGradient.replace(/_/g, ' ');

      // 使用 background 而不是 backgroundImage 以确保兼容性
      style.background = finalGradient;

      if (isTextGradient) {
        style.backgroundClip = 'text';
        style.WebkitBackgroundClip = 'text';
        style.color = 'transparent';
      }

      convertedClasses.push(...complexGradientClassNames);
    }

    // 去重处理，避免重复类名
    const uniqueClassNames = [...new Set(classNames)];

    // 主循环，跳过已被处理的渐变类
    uniqueClassNames.forEach((className) => {
      if (shouldSkipConversion(className)) {
        unconvertedClasses.push(className);
        return;
      }
      if (gradientInfo.isValid && gradientInfo.classNames.includes(className)) return;
      if (complexGradientInfo.isValid && complexGradientInfo.classNames.includes(className)) return;

      // 处理自定义属性格式 [property:value]
      const customPropertyMatch = className.match(/^\[([^:]+):([^\]]+)\]$/);
      if (customPropertyMatch) {
        const [, property, value] = customPropertyMatch;
        style[property] = value;
        convertedClasses.push(className);
        return;
      }

      if (
        parseGenericPadding(className) ||
        parseGenericMargin(className) ||
        parseGenericSize(className) ||
        parseGenericFont(className) ||
        parseGenericBorder(className) ||
        parseBackgroundStyles(className) ||
        parseGenericColor(className) ||
        parseGenericBorderRadius(className) ||
        parseGenericOverflow(className) ||
        parseGenericFlex(className) ||
        parseGenericMinMaxSize(className) ||
        parseGenericBoxShadow(className) ||
        parseGridStyles(className) ||
        parseAnimationStyles(className) ||
        parseInteractionStyles(className) ||
        parseResponsiveStyles(className) ||
        parseDarkModeStyles(className) ||
        parsePrintStyles(className) ||
        parseTextAlign(className) ||
        parseTextDecoration(className) ||
        parseOpacity(className) ||
        parseTextShadowStyles(className) ||
        parsePositionStyles(className) ||
        parseZIndex(className) ||
        parseGapStyles(className) ||
        parseCursorStyles(className) ||
        parseLetterSpacingStyles(className) ||
        parseLineHeightStyles(className) ||
        parseTextTransformStyles(className) ||
        parseWhiteSpaceStyles(className) ||
        parseWordBreakStyles(className) ||
        parseTextOverflowStyles(className) ||
        parseListStyleStyles(className) ||
        parseObjectFitStyles(className) ||
        parseTransformOriginStyles(className)
      ) {
        convertedClasses.push(className);
        return;
      }
      // 如果没有匹配到专门的解析函数，尝试从映射表中查找
      const inlineStyle = enhancedTailwindToStyle[className];
      if (inlineStyle) {
        const [property, value] = inlineStyle.split(':').map((s) => s.trim());
        style[property] = value;
        convertedClasses.push(className);
      } else {
        // 特殊处理自定义背景属性，防止被错误解析为 var(--xxx)
        if (className.startsWith('bg-[')) {
          const customMatch = className.match(/bg-\[([^:]+):([^\]]+)\]/);
          if (customMatch) {
            const [, prop, value] = customMatch;
            if (prop === 'position') {
              style.backgroundPosition = value;
              convertedClasses.push(className);
              return;
            } else if (prop === 'length') {
              style.backgroundSize = value;
              convertedClasses.push(className);
              return;
            } else if (prop === 'repeat') {
              style.backgroundRepeat = value;
              convertedClasses.push(className);
              return;
            }
          }
        }
        unconvertedClasses.push(className);
      }
    });

    // 在开发环境下输出调试信息
    if (process.env.NODE_ENV === 'development') {
      logger('最终样式对象:', style);
      logger('已转换的类名:', convertedClasses);
      logger('未转换的类名:', unconvertedClasses);
      if (errors.length > 0) {
        console.warn('转换错误:', errors);
      }
    }

    const result: InlineStyleResult = {
      style: convertedClasses.length > 0 ? style : undefined,
      convertedClasses,
      unconvertedClasses,
      errors: errors.length > 0 ? errors : undefined,
    };
    return result;
  },

  getPresetStyle: (preset: string) => {
    const presetClasses = presetStyles[preset];
    return presetClasses ? presetClasses.join(' ') : '';
  },
};
